题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

class Solution:
	def FindPath(self , root: TreeNode, target: int) -> List[List[int]]:
    	# write code here
    	if root == None:
        	return 

    	res = self.mySolution(root, target)

    	return res



	def mySolution1(self, root, target):
    	# 迭代-前序遍历
    	# 通过
    	st = []
    	pair = [root, root.val,[root.val]]
    	st.append(pair)
    	res = []
    	while len(st):
        	pair = st.pop()

        	if pair[0].left == None and pair[0].right == None and pair[1] == target:
            	res.append(pair[2])

        	if pair[0].right:
            	st.append([pair[0].right, pair[1] + pair[0].right.val, pair[2] + 	[pair[0].right.val]])

        	if pair[0].left:
            	st.append([pair[0].left, pair[1] + pair[0].left.val, pair[2] + 	[pair[0].left.val]])

    	return res


	def mySolution(self, root, target):
    	# 递归-前序遍历
    	self.res = []
    	def preOrder(root, sum1, path):
        	if root == None:
            	return 

        	if root.left == None and root.right == None and sum1 == root.val:
            	self.res.append(path)
            	return 

        	if root.left == None and root.right == None:
            	return

        	if root.left:
            	preOrder(root.left, sum1-root.val, path+[root.left.val])
        	if root.right:
            	preOrder(root.right, sum1-root.val, path+[root.right.val])

        	return 

    	preOrder(root, target, [root.val])

    	return self.res
    

全部评论

相关推荐

牛客41406533...:回答他在课上学,一辈子待在学校的老教授用三十年前的祖传PPT一字一句的讲解,使用谭浩强红皮书作为教材在devc++里面敲出a+++++a的瞬间爆出114514个编译错误来学这样才显得专业
点赞 评论 收藏
分享
DIY机器人工房:人家叫我骑驴找马
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务