二叉树及遍历效果的实现
本示例二叉树结构如下图:
package structure;
/*
* 树节点对象
*
* 为了缩减代码量 省略了get set方法
*/
class TreeNode {
char data;
TreeNode leftTreeNode;
TreeNode rightTreeNode;
public TreeNode(char data, TreeNode leftTreeNode, TreeNode rightTreeNode) {
this.data = data;
this.leftTreeNode = leftTreeNode;
this.rightTreeNode = rightTreeNode;
}
}
public class BinaryTree {
public static void main(String[] args) {
// 添加树结构
TreeNode H = new TreeNode('H', null, null);
TreeNode K = new TreeNode('K', null, null);
TreeNode D = new TreeNode('D', null, null);
TreeNode C = new TreeNode('C', D, null);
TreeNode B = new TreeNode('B', null, C);
TreeNode G = new TreeNode('G', H, K);
TreeNode F = new TreeNode('F', G, null);
TreeNode E = new TreeNode('E', null, F);
TreeNode A = new TreeNode('A', B, E);
BinaryTree bt = new BinaryTree();
System.out.println("前序遍历");
bt.preEach(A);
System.out.println();
System.out.println("中序遍历");
bt.midEach(A);
System.out.println();
System.out.println("后序遍历");
bt.endEach(A);
System.out.println();
}
// 前序遍历
public void preEach(TreeNode rootNode){
print(rootNode);
if(rootNode.leftTreeNode != null) {
preEach(rootNode.leftTreeNode);
}
if(rootNode.rightTreeNode != null) {
preEach(rootNode.rightTreeNode);
}
}
// 中序遍历
public void midEach(TreeNode rootNode){
if(rootNode.leftTreeNode != null) {
midEach(rootNode.leftTreeNode);
}
print(rootNode);
if(rootNode.rightTreeNode != null) {
midEach(rootNode.rightTreeNode);
}
}
// 后序遍历
public void endEach(TreeNode rootNode){
if(rootNode.leftTreeNode != null) {
endEach(rootNode.leftTreeNode);
}
if(rootNode.rightTreeNode != null) {
endEach(rootNode.rightTreeNode);
}
print(rootNode);
}
// 打印树内容
public void print(TreeNode node) {
System.out.print(node.data);
}
}
附执行结果如下:
前序遍历
ABCDEFGHK
中序遍历
BDCAEHGKF
后序遍历
DCBHKGFEA