前言
最近面临毕业就业,在复习数据结构与算法,为了更好地掌握,加深印象,所以决定写一些博客来知识复现。
温馨提示:这篇博客可能不适合刚学数据结构的新手。
简单说明
- 前序遍历: 先输出父节点,再遍历左子树和右子树
- 中序遍历: 先遍历左子树,再输出父节点,再遍历右子树
- 后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点
- 小结: 看输出父节点的顺序,就确定是前序,中序还是后序
代码实现
package sjjg;
public class BinaryTreePrint {
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryTree2 binaryTree = new BinaryTree2();
HeroNode2 root = new HeroNode2(1, "宋江");
HeroNode2 node2 = new HeroNode2(2, "吴用");
HeroNode2 node3 = new HeroNode2(3, "卢俊义");
HeroNode2 node4 = new HeroNode2(4, "林冲");
HeroNode2 node5 = new HeroNode2(5, "关胜");
root.setLeft(node2);
root.setRight(node3);
node3.setRight(node4);
node3.setLeft(node5);
binaryTree.setRoot(root);
System.out.println("前序遍历-----");
binaryTree.preOrder();
System.out.println("中序遍历-----");
binaryTree.infixOrder();
System.out.println("后序遍历-----");
binaryTree.postOrder();
}
}
//先创建HeroNode 结点
class HeroNode2 {
private int no;
private String name;
private HeroNode2 left; // 默认null
private HeroNode2 right; // 默认null
public HeroNode2(int no, String name) {
this.no = no;
this.name = name;
}
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 HeroNode2 getLeft() {
return left;
}
public void setLeft(HeroNode2 left) {
this.left = left;
}
public HeroNode2 getRight() {
return right;
}
public void setRight(HeroNode2 right) {
this.right = right;
}
@Override
public String toString() {
return "HeroNode [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 infixOrder() {
if (this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if (this.right != null) {
this.right.infixOrder();
}
}
// 后序遍历
public void postOrder() {
if (this.left != null) {
this.left.postOrder();
}
if (this.right != null) {
this.right.postOrder();
}
System.out.println(this);
}
}
class BinaryTree2 {
private HeroNode2 root;
public HeroNode2 getRoot() {
return root;
}
public void setRoot(HeroNode2 root) {
this.root = root;
}
public void preOrder() {
if (this.root != null) {
this.root.preOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
// 中序遍历
public void infixOrder() {
if (this.root != null) {
this.root.infixOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
// 后序遍历
public void postOrder() {
if (this.root != null) {
this.root.postOrder();
} else {
System.out.println("二叉树为空,无法遍历");
}
}
}
结束语
欢迎访问我的博客,一起学习,一起进步!