1. 程式人生 > >劍指offer——(25)二叉樹中和為某一值的路徑

劍指offer——(25)二叉樹中和為某一值的路徑


參考題解: 牛客網
在這裡插入圖片描述

深度優先搜尋(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; } }