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);
    }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章