Tuesday, September 9, 2014

Leetcode: Path Sum @PythonPath Sum

# 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):
        stack=[]
        if root:
            stack=[(root,root.val)]
        else:
            return False
        while stack:
            crt=[]
            for i in stack:
                if i[0].left==None and i[0].right==None and i[1]==sum:
                    return True
                if i[0].left:
                    crt.append((i[0].left,i[1]+i[0].left.val))
                if i[0].right:
                    crt.append((i[0].right,i[1]+i[0].right.val))
            stack=crt
        return False

No comments :

Post a Comment