1、创建节点类
public class Node {
public int data;
public Node left;
public Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
2、二叉树类
public class ConstructTree {
public Node root;
public ConstructTree(){
root = null;
}
//将data插入到排序二叉树
public void insert(int data){
Node newNode = new Node(data);
if(root == null){
root = newNode;
}else{
Node current = root;
Node parent;
while(true){
parent = current;
if(current.data > data){
current = current.left;
if(current == null){
parent.left = newNode;
return ;
}
}else{
current = current.right;
if(current == null){
parent.right = newNode;
return ;
}
}
}
}
}
//将数组输入构建二叉树
public void buildTree(int[] data){
for (int i = 0; i < data.length; i++) {
insert(data[i]);
}
}
//先序遍历
public void preOrder(Node root){
if(root != null){
System.out.print(root.data+" ");
preOrder(root.left);
preOrder(root.right);
}
}
public void preOrder(){
this.preOrder(this.root);
}
//中序遍历
public void inOrder(Node root){
if(root != null){
inOrder(root.left);
System.out.print(root.data+" ");
inOrder(root.right);
}
}
public void inOrder(){
this.inOrder(this.root);
}
//后序遍历
public void postOrder(Node root){
if(root != null){
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+" ");
}
}
//层次遍历
public void layerTranverse(){
if(this.root == null)
return ;
Queue<Node> q = new LinkedList<Node>();
q.add(this.root);
while(!q.isEmpty()){
Node first = q.poll();
System.out.print(first.data+" ");
if(first.left != null){
q.add(first.left);
}
if(first.right != null){
q.add(first.right);
}
}
}
}
3、测试类
public class testTree {
public static void main(String[] args) {
int[] a = {5,2,4,8,6,97,25};
ConstructTree tree = new ConstructTree();
tree.buildTree(a);
System.out.print("先序遍历: ");
tree.preOrder(tree.root);
System.out.println();
System.out.print("中序遍历: ");
tree.inOrder(tree.root);
System.out.println();
System.out.print("后序遍历: ");
tree.postOrder(tree.root);
System.out.println();
System.out.print("层次遍历: ");
tree.layerTranverse();
}
}
4、输出
先序遍历: 5 2 4 8 6 97 25
中序遍历: 2 4 5 6 8 25 97
后序遍历: 4 2 6 25 97 8 5
层次遍历: 5 2 8 4 6 97 25