码疯窝

LeetCode 每日一题 — Path Sum

2014/12/05 10:05:25    分类: 日志连载    3人评论 次浏览

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.

算法分析: sum 从根节点减到叶子看是否为0, 时间复杂度: O(n), 空间复杂度 O(n)

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;
        
        sum -= root.val;
        
        if (sum == 0 && root.left == null && root.right == null)
            return true;
        
        return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    }
}

C++:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if (root == NULL)
            return false;
        
        sum -= root->val;
        
        if (sum == 0 && root->left == NULL && root->right == NULL)
            return true;
        
        return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
    }
};

Python:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @param sum, an integer
    # @return a boolean
    def hasPathSum(self, root, sum):
        if root == None:
            return False
        
        sum -= root.val
        
        if sum == 0 and root.left == None and root.right == None:
            return True
        
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
继续查看有关 日志连载的文章

3个访客评论

  1. 就是赚

    第一次看到,先支持一下

    qweqwe Reply
  2. 112

    good

    qweqwe Reply