2.27 PathSum (leetcode 112) preorder 解法

Posted juanqiuxiaoxiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2.27 PathSum (leetcode 112) preorder 解法相关的知识,希望对你有一定的参考价值。

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 解法的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode]Path Sum II

[leetcode]Path Sum II

6.11 2.27-3.3

[LeetCode] 113. Path Sum II 路径和 II

leetcode 113. Path Sum II (路径和) 解题思路和方法

DFS习题-LeetCode