Friday, September 12, 2014

Leetcode: Path Sum II @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 list of lists of integers
    def pathSum(self, root, sum):
        stack=[]
        if root:
            stack=[([root],root.val)]
        else:
            return []
        rst=[]
        while stack:
            crt=[]
            for i in stack:
                if i[0][-1].left==None and i[0][-1].right==None and i[1]==sum:
                    rst.append([j.val for j in i[0]])
                if i[0][-1].left:
                    temp=i[0]+[i[0][-1].left]
                    crt.append((temp,i[1]+i[0][-1].left.val))
                if i[0][-1].right:
                    temp=i[0]+[i[0][-1].right]
                    crt.append((temp,i[1]+i[0][-1].right.val))
            stack=crt[:]
        return rst

No comments :

Post a Comment