一、二叉树的遍历方式—4种
1、先序遍历—根左右
遍历结果:A-B-D-G-J-P-C-E-H-F-I
2、中序遍历—左根右
遍历结果:D-J-G-P-B-A-H-E-C-I-F
3、后序遍历—左右根
遍历结果:J-P-G-D-B-H-E-I-F-C-A
4、层序遍历—从上到下,从左到右
遍历结果:A-B-C-D-E-F-G-H-I-J-P
二、代码实现
- 节点信息
class Node{
String val;
Node left;
Node right;
public Node(String val) {
this.val = val;
}
}
- 创建一颗二叉树
public static Node build(){
Node a=new Node("A");
Node b=new Node("B");
Node c=new Node("C");
Node d=new Node("D");
Node e=new Node("E");
Node f=new Node("F");
Node g=new Node("G");
Node h=new Node("H");
Node i=new Node("I");
Node j=new Node("J");
Node p=new Node("P");
a.left=b;
a.right=c;
b.left=d;
d.right=g;
g.left=j;
g.right=p;
c.left=e;
c.right=f;
e.left=h;
f.left=i;
return a;
}
1、先序遍历
//先序遍历(“根左右”)
public static void preOrder(Node root){
if(root==null){
return ;
}
//打印根节点
System.out.print(root.val);
//递归遍历左子树
preOrder(root.left);
//递归遍历右子树
preOrder(root.right);
}
递归过程:(以根和左子树为例,右子树同理)
2、中序遍历
//"左根右"
public static void inOrder(Node root){
if(root==null){
return ;
}
//递归遍历左子树
inOrder(root.left);
//打印根节点
System.out.print(root.val);
//递归遍历右子树
inOrder(root.right);
}
3、后序遍历
//后续遍历---"左右根"
public static void postOrder(Node root){
if(root==null){
return ;
}
//递归遍历左子树
postOrder(root.left);
//递归遍历右子树
postOrder(root.right);
//打印根节点
System.out.print(root.val);
}
4、层序遍历
解题思路:
引入一个队列
将根节点入队
队首元素出队并打印
将出队元素的左子树(非空)入队,右子树(非空)入队
public static void levelOrder(Node root){
if(root==null){
return;
}
//引入一个对列
//Queue是一个接口,要new一个实现接口的实例
Queue<Node> queue=new LinkedList<>();
//将根节点入队
queue.offer(root);
//只要队列中有元素,就将队首元素出队并打印
while(true){
Node cur= queue.poll();
//队列为空,跳出循环
if(cur==null){
break;
}
System.out.println(cur.val);
//将出队元素的左子树入队(非空),右子树入队(非空)
if(cur.left!=null) {
queue.offer(cur.left);
}
if(cur.right!=null) {
queue.offer(cur.right);
}
}
}