二叉树从根结点到每个叶子结点都形成一条路径,当然,从任意节点到任意节点也是一条路径,这一类题目较多是我们二叉树问题的重点,也伴随着一些有难度的题目。
递归遍历依次访问树中结点可以构成路径,另外前面提到后序遍历非递归写法的栈中保留当前元素的所有祖先结点。
首先我们看最简单的一道题,所有路径输出:
257. Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
题目解析:
两种解法,一是后序遍历非递归,判断叶子结点,输出栈中元素组成的路径;二是后序遍历递归写法,需要一个内部函数传入当前路径。基本功题目,必须牢记。
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
p = root
stack = []
res = []
while True:
while p:
stack.append(p)
p = p.left
pre = None
f = 1 # 左子树已访问的标记
while stack and f:
p = stack[-1]
if p.right == pre:
if not p.left and not p.right:
path = "->".join([str(x.val) for x in stack])
res.append(path)
stack.pop(-1)
pre = p
else: # 右子树未访问
p = p.right
f = 0
if not stack:
break
return res
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
def helper(root, st):
if root.left:
helper(root.left, st+str(root.val)+str("->"))
if root.right:
helper(root.right, st+str(root.val)+str("->"))
if not root.left and not root.right:
st += str(root.val)
ans.append(st)
return
if not root:
return []
ans = []
helper(root, "")
return ans
113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
题目解析:
路径和等于某个值是一类常见的问题,结合上一题的方法,对路径的值加和,如果该结点为叶结点并且路径中结点值的和刚好等于输入的整数,则当前的路径符合要求。代码参考方法一。
另外的解法,写法千奇百怪,看了几个,认为本质上就是上题的解法二,即为递归方法的二叉树遍历。其思路仍然是,将路径上结点的值累计并传参,遇到叶子结点时比较是否符合要求;不是叶子结点,就递归调用该函数,依次处理左右子树。解法二三都是这种套路,方法二中,当前路径curpath是当前路径,当满足要求时,加入到ans中,需要注意两点,一是`ans.append(curpath[:])` ,ans中必须添加的是curpath的副本,否则指向同一对象就完了;二是在方法三中,实际上将ans作为函数内变量,省去传参的麻烦。类似题目,就写一个内部函数即可,可以免去如方法二将ans, sum都传参的写法。
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
res = []
stack = []
f = 0
s = 0
p = root
while True:
while p:
stack.append(p)
s += p.val
p = p.left
pre = None
f = 1
while stack and f:
p = stack[-1]
if p.right == pre:
if not p.left and not p.right:
if s == sum:
res.append([x.val for x in stack])
stack.pop()
s -= p.val
pre = p
else:
p = p.right
f = 0
if not stack:
return res
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
ans = []
if not root:
return []
self.hp(root,0,[],ans,sum)
return ans
def hp(self,root,cur,curpath,ans,sum):
if not root: #LEAF!
return
else:
curpath.append(root.val)
if cur + root.val==sum and (not root.left and not root.right):
ans.append(curpath[:])
else:
self.hp(root.left,cur+root.val,curpath,ans,sum)
self.hp(root.right,cur+root.val,curpath,ans,sum)
curpath.pop()
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
def dfs(root, arr, subsum):
if not root:
return
if root.left == root.right == None:
if subsum + root.val == sum:
ans.append(arr + [root.val])
else:
dfs(root.left, arr + [root.val], subsum + root.val)
dfs(root.right, arr + [root.val], subsum + root.val)
ans = []
dfs(root, [], 0)
return ans
如上题目是根结点到叶子结点的路径相关问题的解法,谨记递归及非递归写法的套路。
下面我们看一下另一种路径的问题。