java实现排序二叉树的插入及其先序、中序、后序、层次遍历

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 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值