EPI 9.7

This problem is from elements of programming interviews.

Write an inorder traversal without recursion.

In [7]:
class Node:

    def __init__(self,val,left=None,right=None):
        self.val=val
        self.left=left
        self.right=right
        

def inorder_traversal(tree:Node):
    stk=[]
    currNode=tree
    result=[]
    while True:

        while currNode:
            stk.append(currNode)
            currNode=currNode.left
        
        currNode = stk.pop()
        result.append(currNode.val)
        currNode=currNode.right
        if not stk and currNode is None:
            break
    return result

tree=Node(3,Node(4),Node(1,Node(4,Node(7))))

inorder_traversal(tree)
Out[7]:
[4, 3, 7, 4, 1]

Comments

Comments powered by Disqus