参考题解: 牛客网
深度优先搜索(DFS):此题解中,程序执行找到[10, 5, 4]后,4为叶子节点了,remove掉4,变为[10, 5],这时执行if(root.right != null) FindPath(root.right,target); 找到[10, 5, 7],remove掉7,又变为[10, 5],此时会继续执行if(root.right != null) FindPath(root.right,target); 后面的代码,所以又remove掉5,变为[10],后面的同理。
寻找二叉树中值target为22的路径:
root | AL | result |
---|---|---|
10 | [10] |
[] |
5 | [10, 5] |
[] |
4 | [10, 5, 4] |
[] |
5 | [10, 5] |
[] |
7 | [10, 5, 7] |
[10, 5, 7] |
5 | [10, 5] |
[10, 5, 7] |
10 | [10] |
[10, 5, 7] |
12 | [10, 12] |
[[10, 5, 7], [10, 12]] |
10 | [10] |
[[10, 5, 7], [10, 12]] |
10 | [] |
[[10, 5, 7], [10, 12]] |
import java.util.ArrayList;
public class Solution {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> AL = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null || target == 0) return result;
AL.add(root.val);
target = target - root.val;
//依题意加入将符合的路径AL添加到result中
if(target == 0 && root.left == null && root.right == null){
//new一个当前符合题意的路径AL添加进result中 不影响原本的AL
result.add(new ArrayList<Integer>(AL));
}
if(root.left != null) FindPath(root.left,target);
if(root.right != null) FindPath(root.right,target);
// 不管路径符不符合要找的 都要回溯到父节点继续DFS
AL.remove(AL.size()-1);
//DFS全部结束才会返回
return result;
}
public Solution() {
TreeNode node10 = new TreeNode(10);
node10.left = new TreeNode(5);
node10.right = new TreeNode(12);
node10.left.left = new TreeNode(4);
node10.left.right = new TreeNode(7);
FindPath(node10,22);
}
public static void main(String args[]) {
new Solution();
}
}
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}