先序遍历
void preOrder(Node node){
Stack<Node> stack = new Stack<>();
while(node != null || !stack.isEmpty()){
while(node != null){
System.out.println(node.val);
stack.push(node);
node = node.left;
}
if(!stack.isEmpty()){
node = stack.pop();
node = node.right;
}
}
}
中序遍历
void inOrder(Node node){
Stack<Node> stack = new Stack<>();
while(node != null || !stack.isEmpty()){
while(node != null){
stack.push(node);
node = node.left;
}
if(!stack.isEmpty()){
node = stack.pop();
System.out.println(node.val);
node = node.right;
}
}
}
后序遍历
void postOrder(Node node){
Stack<Node> stack = new Stack<>();
Stack<Integer> flag_stack = new Stack<>();
int flag = 1;
while(node != null || !stack.isEmpty()){
while(node != null){
stack.push(node);
flag_stack.push(0);
node = node.left;
}
while(!stack.isEmpty && flag_stack.peek().equals(flag)){
flag_stack.pop();
System.out.println(stack.pop().val);
}
if(!stack.isEmpty()){
flag_stack.pop();
flag_stack.push(1);
node = stack.peek();
node = node.right;
}
}
}