LeetCode劍指offerQ34 二叉樹中和爲某一值的路徑

思路

經典的dfs題目,設置一個變量用來記錄當前路徑上的和count,再用一個list(r)用來記錄當前的路徑。最後只需要在葉子結點時判斷是否count==sum,若相等則將r添加進入最後的結果list,注意添加時需要進行深複製操作,否則僅僅是淺複製,不起效果。同時,深複製的方法一般有循環複製。通過ArratList()初始化函數進行復制有些情況下不行。

代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<List<Integer>> re;
    int sum;
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        re=new ArrayList<>();
          if(root==null) return re;
         
         this.sum=sum;
        dfs(root,0,0,new ArrayList<Integer>());
        return re;
          
    }
    void dfs(TreeNode root,int count,int height,List<Integer> r){
        if(root.left==null&root.right==null){
            count+=root.val;
            r.add(root.val);
            if(count==sum) {  
                List<Integer> rr=new ArrayList<>(r);
            // for(int i=0;i<r.size();i++){
            // rr.add(r.get(i));
            // //System.out.print(r.get(i));
            // }
                re.add(rr);
            }
            r.remove(height);
            return;
        }
        count+=root.val;
        r.add(root.val);
        if(root.left!=null)
              dfs(root.left,count,height+1,r);
        if(root.right!=null)
            dfs(root.right,count,height+1,r);
        r.remove(height);
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章