说明:最烦的就是看别人的博客,题解里直接上代码,一行分析都没有。只是这个题。。。
class BTNode(): def __init__(self, val = -1): self.val = val self.left = None self.right = None class BTree(): def __init__(self): self.root = None ''' ex 1 / 2 3 / / 4 5 treeArray = [1,2,3,4,'#',5] ''' def createTree(self, treeArray): self._createTree(treeArray) def _createTree(self,treeArray, i = 0): if i > len(treeArray) : return None if treeArray[i] == '#': return None root = BTNode(int(treeArray[i])) if self.root == None: self.root = root #create left branch l = 2*i + 1 if l < len(treeArray): root.left = self._createTree(treeArray, l) #create right branch r = 2*i + 2 if r < len(treeArray): root.right = self._createTree(treeArray,r) return root def preorder(self, root): if root == None: return print root.val self.preorder(root.left) self.preorder(root.right) def inorder(self, root): if root == None: return self.inorder(root.left) print root.val self.inorder(root.right) def postorder(self, root): if root == None: return self.postorder(root.left) self.postorder(root.right) print root.val
def Print(path): for i in range(len(path)): print path[i] print "--------------------" def pathSum(broot, remainder, path): if broot == None: return if remainder < broot.val: return path.append(broot.val) remainder -= broot.val if remainder == 0: if broot.left == None and broot.right == None: Print(path) else: return pathSum(broot.left, remainder, path) pathSum(broot.right, remainder,path) path = path.pop() if __name__ == '__main__': array = [10,5,12,4,7] bt = BTree() bt.createTree(array) #bt.preorder(bt.root) path = [] remainder = 22 pathSum(bt.root, remainder, path)