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());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值