本文主要是介绍【剑指offer】Q25:二叉树中和为某一值的路径,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说明:最烦的就是看别人的博客,题解里直接上代码,一行分析都没有,不过这个题。。。
class BTNode():def __init__(self, val = -1):self.val = valself.left = Noneself.right = Noneclass BTree():def __init__(self):self.root = None'''ex1/ \2 3/ /4 5treeArray = [1,2,3,4,'#',5]'''def createTree(self, treeArray):self._createTree(treeArray)def _createTree(self,treeArray, i = 0):if i > len(treeArray) :return Noneif treeArray[i] == '#':return Noneroot = BTNode(int(treeArray[i]))if self.root == None:self.root = root#create left branchl = 2*i + 1if l < len(treeArray):root.left = self._createTree(treeArray, l)#create right branchr = 2*i + 2if r < len(treeArray):root.right = self._createTree(treeArray,r)return rootdef preorder(self, root):if root == None:returnprint root.valself.preorder(root.left)self.preorder(root.right)def inorder(self, root):if root == None:returnself.inorder(root.left)print root.valself.inorder(root.right)def postorder(self, root):if root == None:returnself.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:returnif remainder < broot.val:returnpath.append(broot.val)remainder -= broot.valif remainder == 0:if broot.left == None and broot.right == None:Print(path)else:returnpathSum(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 = 22pathSum(bt.root, remainder, path)
这篇关于【剑指offer】Q25:二叉树中和为某一值的路径的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!