LeetCode 112 Path Sum

题目描述

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,

《LeetCode 112 Path Sum》

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

代码

    static boolean hasPath;

    public static boolean hasPathSum(TreeNode root, int sum) {

        if (root == null) {
            return false;
        }

        hasPath = false;
        help(root, 0, sum);
        return hasPath;
    }

    static void help(TreeNode node, int cur, int sum) {

        cur += node.val;

        boolean isLeaf = (node.left == null) && (node.right == null);

        if (cur == sum && isLeaf) {
            hasPath = true;
        }

        if (node.left != null) {
            help(node.left, cur, sum);
        }

        if (node.right != null) {
            help(node.right, cur, sum);
        }

        cur -= node.val;
    }

更简洁的代码:

    public static boolean hasPathSum2(TreeNode root, int sum) {

        if (root == null) {
            return false;
        }

        if (root.left == null && root.right == null) {
            return root.val == sum;
        }

        return (root.left != null && hasPathSum2(root.left, sum - root.val))
                || (root.right != null && hasPathSum2(root.right, sum
                        - root.val));
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50067587
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞