Problem
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
1 |
|
Follow up: Recursive solution is trivial, could you do it iteratively?
Explanation
-
To do it iteratively, we can create a stack to hold the TreeNode, and a
cur
pointer pointing the root first. We can illustrate the process below:1
2
3
4
51 2 3 4 5 6 x x 7 8 x
-
We first push the current node to the stack, then current node to its left node, push again, update the current node, until current node is null. In other word, now the stack is
[1, 2, 4]
. Then we pop the stack and push pop node’s value tores
, so stack is[1, 2]
,res = [4]
. Then we check if the poped node has right child, if it has right child, then we updatecur
to the right child node and nowcur
node is not null, and we repeate the above process and push it to the stack then update current node to its left node, push again, update the current node, until current node is null. So at some point stack is[1, 2, 7, 8]
,res = [4]
. Then stack is[1, 2, 7]
,res = [4, 8]
, stack is[1, 2]
,res = [4, 8, 7]
, stack is[1]
,res = [4, 8, 7, 2]
, stack is[1, 5]
,res = [4, 8, 7, 2]
, stack is[1]
,res = [4, 8, 7, 2, 5]
, stack is[3]
,res = [4, 8, 7, 2, 5, 1]
, stack is[6]
,res = [4, 8, 7, 2, 5, 1, 3]
, stack is[]
,res = [4, 8, 7, 2, 5, 1, 3, 6]
. -
We end if stack is empty.
Solution
1 |
|