大家首先要明白想要得到先序中序后序遍历分为递归和非递归方法
递归非递归
递归递归方式比较好理解,直接上代码!
//先序遍历
public void f(Node head){
if(head == null){
return;
}
System.out.println(head.val);
f(head.left);
f(head.right);
}
//中序遍历
public void f(Node head){
if(head == null){
return;
}
f(head.left);
System.out.println(head.val);
f(head.right);
}
//后序遍历
public void f(Node head){
if(head == null){
return;
}
f(head.left);
f(head.right);
System.out.println(head.val);
}
非递归
//先序遍历
public void f(Node head){
Stack stack = new Stack();
stack.push(head);
while(!stack.isEmpty()){
Node help = stack.pop();
System.out.print(help.val + " ");
if(help.right != null){
stack.push(help.right);
}
if(help.left != null){
stack.push(help.left);
}
}
System.out.println();
}
//中序遍历
public void f(Node head){
Stack stack1 = new Stack();
Stack stack2 = new Stack();
stack1.push(head);
while(!stack1.isEmpty()){
Node help = stack1.pop();
Stack2.push(help);
if(head.left != null){
stack1.push(head.left);
}
if(head.right != null){
stack1.push(head.rigth);
}
}
while(!stack2.isEmpty()){
System.out.print(stack2.pop().val + " ");
}
System.out.println();
}
//后续遍历
public void f(Node head){
if(head != null){
Stack stack = new Stack();
if(head != null){
stack.push(head);
head = head.left;
} else{
head = stack.pop();
System.out.print(head.val + " ");
head = head.right;
}
}
System.out.println();
}



