1.前序遍历
void preOrderTraversal2(BTNode root){
if(root == null) return;
Stack<BTNode> stack = new Stack<>();
BTNode cur = root;
while (cur!=null||!stack.empty()){
while (cur!=null){
stack.push(cur);
System.out.print(cur.val + " ");
cur = cur.left;
}
BTNode top = stack.pop();
cur = top.right;
}
System.out.println();
}
2.中序遍历(原理同前序遍历)
void inOrderTraversal2(BTNode root){
if(root == null) return;
Stack<BTNode> stack = new Stack<>();
BTNode cur = root;
while (cur!=null||!stack.empty()){
while (cur!=null){
stack.push(cur);
cur = cur.left;
}
BTNode top = stack.pop();
System.out.print(top.val+" ");
cur = top.right;
}
System.out.println();
}
3.后序遍历
void postOrderTraversal2(BTNode root){
if(root == null) return;
Stack<BTNode> stack = new Stack<>();
BTNode cur = root;
BTNode prev = null;
while (cur!=null||!stack.empty()){
while (cur!=null){
stack.push(cur);
cur = cur.left;
}
BTNode top = stack.peek();
if(top.right == null || top.right == prev){
stack.pop();
System.out.print(top.val+" ");
prev = top;
}else {
cur = top.right;
}
}
}