1.前序遍历
前序遍历首先访问根结点然后遍历左子树,最后遍历右子树。在遍历左、右子树时,仍然先访问根结点,然后遍历左子树,最后遍历右子树。
若二叉树为空则结束返回,否则:
(1)访问根结点;
(2)前序遍历左子树;
(3)前序遍历右子树 ;
需要注意的是:遍历左右子树时仍然采用前序遍历方法。可以看出前序遍历后,遍历结果为:631254978
2.中序遍历
中序遍历首先遍历左子树,然后访问根结点,最后遍历右子树。在遍历左、右子树时,仍然先遍历左子树,再访问根结点,最后遍历右子树。即:
若二叉树为空则结束返回,否则:
(1)中序遍历左子树;
(2)访问根结点;
(3)中序遍历右子树;
注意的是:遍历左右子树时仍然采用中序遍历方法。最上图的二叉树用中序遍历的结果是:123456789
3.后续遍历
后序遍历首先遍历左子树,然后遍历右子树,最后访问根结点,在遍历左、右子树时,仍然先遍历左子树,然后遍历右子树,最后遍历根结点。即:
若二叉树为空则结束返回,否则:
(1)后序遍历左子树;
(2)后序遍历右子树;
(3)访问根结点;
如图所示的二叉树,用后序遍历的结果是:214538796
//递归版本
public void preOrderRecur(Node head){//先序
if(head==null){
return;
}
System.out.println(head.value);
preOrderRecur(head.left);
preOrderRecur(head.right);
}
public void inOrderRecur(Node head){//中序
if(head==null){
return;
}
inOrderRecur(head.left);
System.out.println(head.value);
inOrderRecur(head.right);
}
public void posOrderRecur(Node head){//后序
if(head==null){
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.println(head.value);
}
//非递归版本
public void preOrderUnRecur(Node head){//先序
if(head==null){
return;
}
Stack<Node> stack=new Stack<Node>();
stack.push(head);
while (!stack.isEmpty()){
Node temp=stack.pop();
System.out.println(temp.value);
if(temp.right!=null){
stack.push(temp.right);
}
if(temp.left!=null){
stack.push(temp.left);
}
}
}
public void inOrderUnRecur(Node head){//中序
if(head==null){
return;
}
Stack<Node> stack=new Stack<>();
while (!stack.isEmpty()||head!=null){
if(head!=null){
stack.push(head);
head=head.left;
}else {//左子树为空,打印
head=stack.pop();
System.out.println(head.value);
head=head.right;
}
}
}
public void posOrderUnRecur(Node head){//后序
if(head==null){
return;
}
Stack<Node> stack1=new Stack<>();
Stack<Node> stack2=new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()){
Node temp=stack1.pop();
stack2.push(temp);
if(temp.left!=null){
stack1.push(temp.left);
}
if(temp.right!=null){
stack1.push(temp.right);
}
}
while (!stack2.isEmpty()){
System.out.println(stack2.pop().value);
}
}
参考:https://blog.csdn.net/weixin_37730482/article/details/70677638