一、二叉树手动遍历
1.前序遍历2.中序遍历3.后续遍历 二、Java代码实现
一、二叉树手动遍历 1.前序遍历口诀:中左右 --->先写中节点,然后左节点 最后右节点 中表示根节点 左表示左节点 右表示右节点 遍历结果:12453672.中序遍历
口诀:左中右 --->先写左节点,然后中节点 最后右节点 中表示根节点 左表示左节点 右表示右节点 遍历结果:42516373.后续遍历
口诀:左右中 --->先写左节点,然后右节点 最后中节点 中表示根节点 左表示左节点 右表示右节点 遍历结果:4526731
二、Java代码实现每个节点的组成:
树的组成:
class Node{
public int no; //data域
public Node left; //左节点
public Node right; //右节点
public Node(int no) {
this.no = no;
}
//前序遍历 按照:中左右遍历
public void preShow(){
if (this==null){
System.out.println("该树为空!");
return; //方法执行结束
}
System.out.print(this.no+" "); //输出节点
if(this.left!=null){//遍历左节点
this.left.preShow();
}
if (this.right!=null){ //遍历右节点
this.right.preShow();
}
}
//中序遍历 按照:左中右遍历
public void infixShow(){
if (this==null){
System.out.println("该树为空!");
return;
}
if (this.left!=null){ //遍历左节点
this.left.infixShow();
}
System.out.print(this.no+" ");
if (this.right!=null){ //遍历右节点
this.right.infixShow();
}
}
//后序遍历 按照:左右中遍历
public void postShow(){
if (this==null){
System.out.println("该树为空!");
return;
}
if (this.left!=null){
this.left.postShow();
}
if (this.right!=null){
this.right.postShow();
}
System.out.print(this.no+" ");
}
}
**测试代码:**
public static void main(String[] args) {
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
Node n5=new Node(5);
Node n6=new Node(6);
Node n7=new Node(7);
n1.left=n2;
n1.right=n3;
n2.left=n4;
n2.right=n5;
n3.left=n6;
n3.right=n7; //通过指向形成二叉树
n1.preShow(); //前序遍历
System.out.println("");
n1.infixShow(); //中序遍历
System.out.println("");
n1.postShow(); //后序遍历
}
结果:



