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

劍指offer-二叉樹中和為某一值的路徑

24.二叉樹中和為某一值的路徑

題目描述

輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,陣列長度大的陣列靠前)

解題思路:本題可用深度優先遍歷,從根結點出發,依次向下找,若找到其中的一條路為路徑,則將其列印,然後回退到上一個結點,再去此結點的另一棵子樹上去找。

public class Solution {
     ArrayList<ArrayList<Integer>> res=new ArrayList<>();
     ArrayList<Integer> list=new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root==null)
            return res;
        list.add(root.val);
        target=target-root.val;
        if(target==0 && root.left==null && root.right==null)
            res.add(new ArrayList<>(list));
        FindPath(root.left,target);
        FindPath(root.right,target);
        list.remove(list.size()-1);
        return res;     
    }
}