173. Binary Search Tree Iterator
# Medium
Use interative instead of recursive to do inorder traversal by stack.
Solution:
If binary tree is a valid binary tree, left subtree is bigger than root, right subtree is bigger than root. Inorder traversal of this binary tree is ascending order.
Start from root, push all left nodes to stack.
[7, 3, 1]
Pop out one node from stack, declare
node.right
as new root, then add all left nodes of that new root to stack.stack =
[7, 3, 2]
result =[1]
stack =
[7, 3]
result =[1,2]
stack =
[7, 5, 4]
result =[1,2,3]
stack =
[7, 5]
result =[1,2,3,4]
stack =
[7, 6]
result =[1,2,3,4,5]
stack =
[7]
result =[1,2,3,4,5,6]
stack =
[10, 8]
result =[1,2,3,4,5,6,7]
stack =
[10]
result =[1,2,3,4,5,6,7,8]
stack =
[12, 11]
result =[1,2,3,4,5,6,7,8,10]
stack =
[12]
result =[1,2,3,4,5,6,7,8,10,11]
result =
[1,2,3,4,5,6,7,8,10,11,12]
Last updated