sword_for_offer/docs/剑指 Offer 34. 二叉树中和为某一值的路径.md
本题是典型的二叉树方案搜索问题,使用回溯法解决,其包含 先序遍历 + 路径记录 两部分。
sum 时,将此路径加入结果列表。{:width=500}
pathSum(root, sum) 函数:
res ,路径列表 path 。res 即可。recur(root, tar) 函数:
root ,当前目标值 tar 。root 为空,则直接返回。root.val 加入路径 path 。tar = tar - root.val(即目标值 tar 从 sum 减至 $0$ )。root 为叶节点 且 ② 路径和等于目标值 ,则将此路径 path 加入 res 。path 中删除,即执行 path.pop() 。<,,,,,,,,,,,>
path 存储所有树节点,使用 $O(N)$ 额外空间。以 Python 语言为例,记录路径时若直接执行 res.append(path) ,则是将此 path 对象加入了 res ;后续 path 改变时, res 中的 path 对象也会随之改变,因此无法实现结果记录。正确做法为:
res.append(list(path)) ;res.add(new LinkedList(path)) ;res.push_back(path) ;三者的原理都是避免直接添加
path对象,而是 拷贝 了一个path对象并加入到res。
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res, path = [], []
def recur(root, tar):
if not root: return
path.append(root.val)
tar -= root.val
if tar == 0 and not root.left and not root.right:
res.append(list(path))
recur(root.left, tar)
recur(root.right, tar)
path.pop()
recur(root, sum)
return res
class Solution {
LinkedList<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recur(root, sum);
return res;
}
void recur(TreeNode root, int tar) {
if(root == null) return;
path.add(root.val);
tar -= root.val;
if(tar == 0 && root.left == null && root.right == null)
res.add(new LinkedList(path));
recur(root.left, tar);
recur(root.right, tar);
path.removeLast();
}
}
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
recur(root, sum);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void recur(TreeNode* root, int tar) {
if(root == nullptr) return;
path.push_back(root->val);
tar -= root->val;
if(tar == 0 && root->left == nullptr && root->right == nullptr)
res.push_back(path);
recur(root->left, tar);
recur(root->right, tar);
path.pop_back();
}
};