樹-回溯-面試題34. 二叉樹中和爲某一值的路徑

 

 

解題思路: 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    LinkedList<List<Integer>> res= new LinkedList<>();
    LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        recu(root,sum);
        return res;
    }
    void recu(TreeNode root,int tar){
        if(root==null) return;
        path.add(root.val);
        tar=tar-root.val;
        if(tar==0&&root.left==null&&root.right==null) 
            res.add(new LinkedList(path));
        recu(root.left,tar);
        recu(root.right,tar);
        path.removeLast();   //Object removeLast()刪除列表中最後一個元素 
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章