using stack iteratively traverse by python,not change the node


  • 0
    M
    # 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]
            """
            if not root:
                return []
            return_list = []
            stack = [root]
    
            while stack:
                p = stack[-1].left
                while p:
                    stack.append(p)
                    p = p.left
                while stack and not stack[-1].right:
                    return_list.append(stack[-1].val)
                    del(stack[-1])
                if stack:
                    return_list.append(stack[-1].val)
                    tmp = stack[-1].right
                    del(stack[-1])
                    stack.append(tmp)
    
            return return_list
    
    

Log in to reply
 

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