码迷,mamicode.com
首页 > 其他好文 > 详细

2.27 PathSum (leetcode 112) preorder 解法

时间:2018-02-28 10:40:21      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:values   tree   node   一个   case   public   leetcode   结果   null   

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \              7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

这道题可以用pre-order对于二叉树自上到下来递归,每次递归生成一个减掉root.val的新sum,然后先判断sum是否为零并且当前的root是否为leaf,若满足则return true,否则对其左儿子和右儿子分别递归,返回左儿子结果||右儿子结果,如此往复直到root是null(本身是leaf,此时返回false)。

class Solution{
    public boolean hasPathSum(TreeNode root, int sum){
        // base case
        if(root == null){
            return false;
        }
        int newSum = sum - root.val;
        if (newSum == 0 && root.left == null && root.right == null){
            return true;
        }
        boolean left = hasPathSum(root.left, newSum);
        boolean right = hasPathSum(root.right, newSum);
        return left || right;
    }
}

 

2.27 PathSum (leetcode 112) preorder 解法

标签:values   tree   node   一个   case   public   leetcode   结果   null   

原文地址:https://www.cnblogs.com/juanqiuxiaoxiao/p/8481749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!