Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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] ]
好好理解下先序遍历
Pre-order[edit]
- Check if the current node is empty / null
- Display the data part of the root (or current node).
- Traverse the left subtree by recursively calling the pre-order function.
- Traverse the right subtree by recursively calling the pre-order function
所以读的顺序是5,4,11,7,2,8,13,4,5,1。
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
实际上是
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
/ \ / \/ \ / \
n n n nn n n n
当dfs进入到leaf层,就会dfs(leaf.left) leaf.left==null return. dfs(leaf.right) leaf.right==null,return. 这时候进行回溯操作,check.remove(check.size()-1);就会把7移走。
然后从null层返回到leaf层,这时候dfs(11.left)运行完了,运行dfs(11.right),同理。
因此可以看出先序遍历之后进行回溯操作是对leaf node的操作。这样就很容易理解solution2.
重点是理解先序遍历后的回溯操作是针对LEAF的。
细化版理解:
leaf node:先序遍历,先加root,然后遍历左右子树,如果都为null(遍历完),回溯去掉4。
4
/ \
null null
GOOD REF:https://www.youtube.com/watch?v=gm8DUJJhmY4
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res=new ArrayList<>(); List<Integer> check=new ArrayList<Integer>(); dps(root,res,check,sum); return res; } public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum) { if(root==null) { return; } check.add(root.val); if(root.left==null&&root.right==null&&sum==root.val) { res.add(new ArrayList<>(check)); } else { dps(root.left,res,check,sum-root.val); dps(root.right,res,check,sum-root.val); } check.remove(check.size()-1); } }
Solution2:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res=new ArrayList<>(); List<Integer> check=new ArrayList<Integer>(); dps(root,res,check,sum); return res; } public void dps(TreeNode root, List<List<Integer>> res,List<Integer> check,int sum) { if(root==null) { return; } if(root.left==null&&root.right==null) { if(sum==root.val) { List<Integer> tmp=new ArrayList<>(check); tmp.add(root.val); res.add(tmp); } return; } check.add(root.val); dps(root.left,res,check,sum-root.val); dps(root.right,res,check,sum-root.val); check.remove(check.size()-1); } }