public class TreeTest {
class TreeNode {
int val;
TreeNode leftNode;
TreeNode rightNode;
public TreeNode(int val) {
this.val = val;
leftNode = null;
rightNode = null;
}
}
private TreeNode root = null;
/*构建一棵二叉排序树*/
public void buildTree(int[] array) {
for(int i=0; i<array.length; i++) {
insertNode(array[i]);
}
}
public void insertNode(int data) {
TreeNode newNode = new TreeNode(data);
if(root == null) {
root = newNode;
} else {
TreeNode current = root;
TreeNode parent;
while(true) {
parent = current;
if(data < current.val) {
current = current.leftNode;
if(current == null) {
parent.leftNode = newNode;
return;
}
} else {
current = current.rightNode;
if(current == null) {
parent.rightNode = newNode;
return;
}
}
}
}
}
/**
* 先序遍历
* */
public void firstTrace(TreeNode root) {
if(root != null) {
System.out.print(root.val+" ");
firstTrace(root.leftNode);
firstTrace(root.rightNode);
}
}
public void firstTrace() {
this.firstTrace(this.root);
}
/**
* 中序遍历
* */
public void midTrace(TreeNode root) {
if(root != null) {
midTrace(root.leftNode);
System.out.print(root.val+" ");
midTrace(root.rightNode);
}
}
public void midTrace() {
this.midTrace(root);
}
/**
* 后序遍历
* */
public void postTrace(TreeNode root) {
if(root != null) {
postTrace(root.leftNode);
postTrace(root.rightNode);
System.out.print(root.val+" ");
}
}
public void postTrace() {
this.postTrace(root);
}
/**
* 测试
* */
public static void main(String[] args) {
TreeTest tt = new TreeTest();
int[] array = {2, 8, 7, 4, 9, 3, 1, 6, 7, 5};
tt.buildTree(array);
tt.firstTrace(); System.out.println();
tt.midTrace(); System.out.println();
tt.postTrace();
}
}
实现二叉排序树, 并分别用先序、中序、后序输出
最新推荐文章于 2020-11-18 20:38:20 发布