首页 > ACM题库 > LeetCode > Path Sum-LeetCode
2014
08-29

Path Sum-LeetCode

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      1

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

题目链接:https://oj.leetcode.com/problems/path-sum/

经典的题目了,二叉树的题目一般都是用递归。关键是找到基本情况。注意题目要求的路径必须是到叶节点。

Java代码如下:

/**
 * Definition for binary tree
 * 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)
            return (root.val == sum);

        return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
    }
}