O(1) SPACE Python solution


  • 0
    Y
    # 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 inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            ret = []
            cur = root
            prev = None
            while cur is not None:
                if cur.left is None:
                   ret.append(cur.val)
                   cur = cur.right
                else:
                   prev = cur.left
                   while prev.right is not None and prev.right != cur:
                       prev = prev.right
                   if prev.right is None:
                      prev.right = cur
                      cur = cur.left
                   else:
                      prev.right = None
                      ret.append(cur.val)
                      cur = cur.right       
            return ret

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.