LeetCode 112 Path Sum

来源:互联网 发布:中频治疗仪 知乎 编辑:程序博客网 时间:2024/05/18 05:20

题目描述

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.

代码

    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));    }
1 0