题目描述:
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
简洁版:
– 注意到路径必须为跟节点 –> 没有左右子树的叶子节点;定义两个数组pathArray、onePath,pathArray用于存储所有符合条件的路径,onePath用于存储当前遍历的路径;
– 类似于深度优先搜索,每遍历到一个节点,就将其加入到onePath中,并判定是否符合条件:
- 为叶节点且和等于要求的整数,则将该数组存储至pathArray中,并换其他路径继续搜寻;
- 和小于要求的整数,则向当前节点的左右子树依次深度优先搜索;
- 和大于要求的整数,则直接换路搜索。
// An highlighted block
class Solution:
def __init__(self):
self.onePath = []
self.PathArray = []
def FindPath(self, root, expectNumber):
if root is None:
return self.PathArray
self.onePath.append(root.val)
expectNumber -= root.val
if expectNumber==0 and not root.left and not root.right:
self.PathArray.append(self.onePath[:])
elif expectNumber>0:
self.FindPath(root.left,expectNumber)
self.FindPath(root.right,expectNumber)
self.onePath.pop()
return self.PathArray
地址:
https://blog.csdn.net/a787264137/article/details/78658493
思路:
递归前序遍历树, 把结点加入路径。使用列表结构存树结构;
若该结点是叶子结点则比较当前路径和是否等于期待和,叶子节点说明该路径应该截止了;
弹出结点,每一轮递归返回到父结点时,当前路径也应该回退一个结点。
// An highlighted block
class Solution:
# 返回二维列表,内部每个列表表示找到的路径
def FindPath(self, root, expectNumber):
# write code here
if not root:
return []
result = []
def FindPath2(root, path, currentNum):
currentNum += root.val
# root使用append转成了列表,因为最后要一个序列,root本身还是树结构
path.append(root)
# 判断是不是到叶子节点了,到叶子节点了就要判断值的和是不是相等
flag = root.left == None and root.right == None
# 返回值是一个等于整数的序列
if currentNum == expectNumber and flag:
onepath = []
for node in path:
onepath.append(node.val)
result.append(onepath)
if currentNum < expectNumber:
if root.left:
FindPath2(root.left, path, currentNum)
if root.right:
FindPath2(root.right, path, currentNum)
# 拿到一个正确的路径后要弹出,回到上一次父节点继续递归
path.pop()
FindPath2(root, [], 0)
return result
```