剑指 Offer 34. 二叉树中和为某一值的路径
思路:前序遍历
dfs前序遍历二叉树,记录每条路径是否满足和为sum,不满足则删去该结点,回溯到上一个结点。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { LinkedList<List<Integer>> res = new LinkedList<>(); LinkedList<Integer> path = new LinkedList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { helper(root, sum); return res; } void helper(TreeNode root, int sum){ if (root == null) return; path.add(root.val); sum -= root.val; if (sum == 0 && root.left == null && root.right == null) res.add(new LinkedList(path)); helper(root.left, sum); helper(root.right, sum); path.removeLast(); } }
需注意的点:
记录路径时若直接执行 res.add(path) ,则是将 path 对象加入了 res ;后续 path 改变时, res 中的 path 对象也会随之改变。
正确做法:res.add(LinkedList(path)) ,相当于复制了一个 path 并加入到 res 。