您的位置:首页 > 其它

LeetCode 112 Path Sum

2015-11-27 10:59 411 查看

题目描述

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,



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

代码

[code]    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;
    }


更简洁的代码:

[code]    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));
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: