Skip to content

Latest commit

 

History

History
123 lines (93 loc) · 2.54 KB

112. Path Sum.md

File metadata and controls

123 lines (93 loc) · 2.54 KB

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.

Note: A leaf is a node with no children.

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.

Solution

code1是递归继续作弊一般的简单><

code2也是递归,更加简单,不需要helper了。

code3是迭代。10/23.

Code1

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

def helper(root,cur_val,result):
    if root is None:
        return
    if root.left is None and root.right is None:
        result.append(cur_val+root.val)
        
    if root.left:
        helper(root.left,cur_val+root.val,result)
    if root.right:
        helper(root.right,cur_val+root.val,result)
        
    
    
class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        result = []
        helper(root,0,result)
        
        # print(result)
        return sum in result

Code2

class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root is None:
            return False
        if root.left is None and root.right is None and root.val == sum:
            return True
        sum -= root.val
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)

Code3

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

class Solution(object):
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """            
        stack = []
        if root is None:
            return False
        stack.append([root,sum])
        while stack:
            node, value = stack.pop(0)
            if not node.left and not node.right and node.val == value:
                return True
            if node.left:
                stack.append([node.left, value-node.val])
            if node.right:
                stack.append([node.right, value-node.val])
        return False