lintcode376-二叉樹的路徑和

  Question:
  給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值 的路徑。
  一個有效的路徑,指的是從根節點到葉節點的路徑。
  樣例
  給定一個二叉樹,和 目標值 = 5:
       1
      / \
     2   4
    / \
   2   3
     返回:

     [
     [1, 2, 2],
     [1, 4]
     ]
     
  Solution:
  本題與Q480題一樣,都是用到深度優先搜索查詢全路徑,在Q480的基礎上再加一點點限制條件,即幾個節點的和等於給定值
 

public class Q376_binaryTreePathSum {
    
    public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root == null)
            return result;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode current = root;
        TreeNode pre = null;
        while(current != null || !stack.isEmpty()) {
            if(current != null) {
                stack.push(current);
                current = current.left;
            } else {
                current = stack.peek();
                if(current.right != null && pre != current.right) {
                    current = current.right;
                } else {
                    current = stack.pop();
                    if(current.left == null && current.right == null) {
                        int sum = 0;
                        List<Integer> res = new ArrayList<Integer>();
                        for(TreeNode t : stack) {
                            sum += t.val;
                            res.add(t.val);
                        }
                        sum += current.val;
                        res.add(current.val);
                        if(sum == target) {
                            result.add(res);
                        }
                    }
                    pre = current;
                    current = null;
                }
            }
        }
        return result;
    }

    @Test
    public void test() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(5);
        root.left.left = new TreeNode(4);
        root.right = new TreeNode(3);
        List<List<Integer>> result = binaryTreePathSum(root,7);
        System.out.println(result.toString());
    }
}

 

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