往
期
回
顾
1.手动写web服务器资料(速领)
2.MyBatisPlus资料
3.头条一面汇总(一)
5.JVM相关总结
遍历二叉树是指按照某一条路径搜寻树中的每一个节点,使得每一个节点均被访问一次,而且仅仅访问一次,遍历有三种方式:先序遍历、中序遍历、后序遍历。
先序遍历二叉树的操作定义:
若二叉树为空,则空操作;否则:
(1)先访问根节点。
(2)先序遍历左子树
(3)先序遍历右子树
中序遍历二叉树的操作定义:
若二叉树为空,则空操作;否则:
(1)中序遍历左子树
(2)访问根节点
(3)中序遍历右子树
后序遍历二叉树的操作定义:
若二叉树为空,则空操作;否则:
(1)后续遍历左子树
(2)后序遍历右子树
(3)访问根节点
如下图所示:
先序遍历结果:A B D C E
中序遍历结果:D B A C E
后续遍历结果:D B E C A
源码:
节点类
package com.demo;
public class Node {
private int no;
private String name;
private Node left; //左节点
private Node right; //有节点
public Node(int no, String name) {
this.no = no;
this.name = name;
}
public Node(int no, String name, Node left, Node right) {
this.no = no;
this.name = name;
this.left = left;
this.right = right;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
//先序遍历的方法
public void preOrder(){
//父节点
System.out.println(this);
//左子树
if (this.left !=null){
this.left.preOrder();
}
//右子树
if (this.right !=null){
this.right.preOrder();
}
}
//中序遍历
public void midOrder(){
//左子树
if (this.left !=null){
this.left.midOrder();
}
//父节点
System.out.println(this);
//右子树
if (this.right !=null){
this.right.midOrder();
}
}
//后续遍历
public void postOrder(){
//左子树
if (this.left != null){
this.left.postOrder();
}
//右子树
if (this.right !=null){
this.right.postOrder();
}
//父节点
System.out.println(this);
}
}
2.二叉树
public class Binary {
private Node root;
public void setRoot(Node root) {
this.root = root;
}
public Node getRoot() {
return root;
}
//先序
public void preNode(){
if (root !=null){
this.root.preOrder();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
//中序
public void midNode(){
if (root !=null){
this.root.midOrder();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
//后续
public void postNode(){
if (root !=null){
this.root.postOrder();
}else {
System.out.println("二叉树为空,无法遍历");
}
}
}
3.测试
public class TestOrder {
public static void main(String[] args) {
//创建二叉树
Binary binary = new Binary();
//创建节点
Node root = new Node(1,"A");
Node node1 = new Node(2,"B");
Node node2 = new Node(3,"C");
Node node3 = new Node(4,"D");
Node node4 = new Node(5,"E");
//手动创建
binary.setRoot(root);
root.setLeft(node1);
root.setRight(node2);
node1.setLeft(node3);
node2.setRight(node4);
System.out.println("先序遍历:");
binary.preNode();
System.out.println("后序遍历:");
binary.midNode();
System.out.println("后续遍历:");
binary.postNode();
}
先序遍历的结果为:
中序遍历的结果:
后序遍历的结果:
关注我
获取更多
Java干货
原创文章
视频资料
技术交流群