【剑指offer】Q25:二叉树中和为某一值的路径
来源:互联网 发布:如何做读书笔记 知乎 编辑:程序博客网 时间:2024/06/05 00:19
说明:最烦的就是看别人的博客,题解里直接上代码,一行分析都没有,不过这个题。。。
class BTNode():def __init__(self, val = -1):self.val = valself.left = Noneself.right = Noneclass 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 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 root def 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)
0 0
- 【剑指offer】Q25:二叉树中和为某一值的路径
- Q25:二叉树中和为某一值的路径
- Q25:二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值的路径
- 剑指offer--二叉树中和为某一值的路径
- 《剑指offer》二叉树中和为某一值的路径
- 【剑指Offer】二叉树中和为某一值的路径
- 剑指Offer--二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- [剑指offer]二叉树中和为某一值的路径
- 《剑指offer》-二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值的路径
- 剑指offer|二叉树中和为某一值的路径
- 《剑指offer》二叉树中和为某一值的路径
- 递归
- C++ 的嵌套友元
- Java WebService入门实例
- 燃
- ubuntu git 使用
- 【剑指offer】Q25:二叉树中和为某一值的路径
- 《电子商务》漫谈网络营销
- asp.net获取客户端信息
- 在英文版的linux系统下,安装google浏览器出现乱码解决方法
- 一个让她泪流满面的礼物
- C#中的内存管理(三)垃圾回收
- Codefoces 436 B. Om Nom and Spiders
- Linux 0.12 任务长度由640KB到64M的fork转变
- Web 建站技术中,HTML、HTML5、XHTML、CSS、SQL、JavaScript、PHP、ASP.NET、Web Services 区别