题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路
(1)将根节点加入临时路径中;
(2)判断根节点是不是叶子节点,是叶子节点,在判断是否满足和,满足则加入路径;
(3)不是叶子节点,递归遍历左右子树
代码实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
ret=[]
#深度优先搜索算法
def dfs(root,sum_,tmp):
if root:
if root.left==None and root.right==None:
if root.val==sum_:
tmp.append(root.val)
ret.append(tmp[:])
else:
tmp.append(root.val)
dfs(root.left,sum_-root.val,tmp[:])
dfs(root.right,sum_-root.val,tmp[:])
dfs(root,expectNumber,[])
return ret
递归先序遍历树,把结点加入路径。若该结点是叶子节点则比较路径和与给定值是否相等。相等则加入路径。回退到父节点,路径作为下一次递归操作的路径。
链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root: #树为空
return []
result = []
def FindPathMain(root, path, currentSum):
currentSum += root.val
path.append(root)
isLeaf = root.left == None and root.right == None
if currentSum == expectNumber and isLeaf: #是叶节点且满足和
onePath = []
for node in path:
onePath.append(node.val)
result.append(onePath)
if currentSum < expectNumber: #不满足和,继续判断是否有左右子树,继续递归操作
if root.left:
FindPathMain(root.left, path, currentSum)
if root.right:
FindPathMain(root.right, path, currentSum)
path.pop() #返回父节点
FindPathMain(root, [], 0)
return result
同样递归的做法
链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
res=[]
treepath=self.dfs(root)
for i in treepath:
if sum(map(int,i.split('->')))==expectNumber:
res.append(list(map(int,i.split('->'))))
return res
def dfs(self, root):
if not root: return []
if not root.left and not root.right:
return [str(root.val)]
treePath = [str(root.val) + "->" + path for path in self.dfs(root.left)]
treePath += [str(root.val) + "->" + path for path in self.dfs(root.right)]
return treePath
上边程序的精简版
链接:https://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
来源:牛客网
class Solution:
def FindPath(self, root, expectNumber):
return [map(int, i.split("->")) for i in self.dfs(root) if sum(map(int, i.split('->'))) == expectNumber]
def dfs(self, root):
if not root: return []
if not root.left and not root.right: return [str(root.val)]
treePath = [str(root.val) + "->" + path for path in self.dfs(root.left)]
treePath += [str(root.val) + "->" + path for path in self.dfs(root.right)]
return treePath