leetcode112. Path Sum

来源:互联网 发布:看股票用什么软件 知乎 编辑:程序博客网 时间:2024/06/07 03:32

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,              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

解法一

找到叶子结点,判断累加和是否等于target。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int target;    boolean ret;    public boolean hasPathSum(TreeNode root, int sum) {        target = sum;        if (root == null) {            return false;        }        helper(root, root.val);        return ret;    }    public void helper(TreeNode root, int sum) {        if (root.left == null && root.right == null) {            if (sum == target) {                ret = true;                return;            }        }        if (root.left != null)            helper(root.left, sum + root.left.val);        if (root.right != null)            helper(root.right, sum + root.right.val);    }}

解法二

dfs,每次减去该结点的值,直到叶子结点,判断是否值为0。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        if (root == null) {            return false;        }        if (root.left == null && root.right == null && sum - root.val == 0) {            return true;        }        return hasPathSum(root.left, sum - root.val)         || hasPathSum(root.right, sum - root.val);    }}
原创粉丝点击