zoukankan      html  css  js  c++  java
  • 【剑指offer】Q25:二叉树中和为某一值的路径

    说明:最烦的就是看别人的博客,题解里直接上代码,一行分析都没有。只是这个题。。。快哭了

    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)
    


  • 相关阅读:
    使 Asp.net Core Hosting Bundle 立即生效
    Hosted Services require keep alive
    VS 高级保存选项,解决文件内容编码问题
    asp.net core localhost https 证书
    阿里云K8S下玩.NET CORE 3.1
    cmd 域名生效检测
    c# 通过win32 api 得到指定Console application Content
    .net framework msbuild环境搭建 (不装vs)
    Python常用模块——目录
    Python——爬虫进阶
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5157885.html
Copyright © 2011-2022 走看看