• 【剑指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)
    


  • 相关阅读:
    Ubuntu 18.04安装gcc、g++ 4.8
    Java 接口返回值集合防止空指针
    Linux CentOS7.9环境下搭建Java Web 环境
    Springboot集成UReport2
    linux 环境中 单独执行 python 脚本
    sql 注入的问题
    检验上传文件的大小
    Gunicorn使用讲解
    CentOS下安装部署对象存储服务MinIO
    阿里云CentOS7安装MySQL
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5157885.html
Copyright © 2020-2023  润新知