Tuesday, September 9, 2014

Leetcode: Flatten Binary Tree to Linked List @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
    # @return nothing, do it in place
    def flatten(self, root):
        stack=[]
        crt=root
        while crt:
            if crt.right:
                stack.append(crt.right)
                crt.right=None
            if crt.left:
                crt.right=crt.left
                crt.left=None
                crt=crt.right
            else:
                if stack:
                    crt.right=stack.pop()
                    crt=crt.right
                else:
                    break

No comments :

Post a Comment