Tree traversal: In-order traversal non-recursion
如果有一棵樹 [1, 2, 3, 4, 5, 6] 要做 inorder traversal non-resursion
虛擬算法如下:
- initialize a stack and push root into it.
- initialize a cur TreeNode and set its value to root.
- push all cur's left children into stack if any.
- pop a element from stack and print it.
- if the element has right, push it into stack and go back to 3.
public void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> S = new Stack<TreeNode>(); //1
TreeNode cur; //2
while (true) {
while (cur != null) { //3
S.push(cur);
cur = cur.left;
}
if (S.isEmpty()) {
break;
}
cur = S.pop(); //4
System.out.print(node.val);
cur = cur.right; //5
}
return;
}