Java实现顺序存储二叉树及其前序、中序、后序遍历

点击进入尚硅谷数据结构和算法Java代码导航

//顺序存储二叉树,完全二叉树
class arrayTree{
	Node[] at;
	//bt为完全二叉树
	public arrayTree(BinaryTree bt){
		ArrayDeque<Node> quene = new ArrayDeque<Node>();
		int count = 0;
		Node temp = bt.root;
		quene.add(temp);
		while(!quene.isEmpty()) {
			temp = quene.poll();
			count++;
			if(temp.left != null) {
				quene.add(temp.left);
			}
			if(temp.right != null) {
				quene.add(temp.right);
			}
		}
		at = new Node[count];
		count = 0;
		temp = bt.root;
		quene.add(temp);
		while(!quene.isEmpty()) {
			temp = quene.poll();
			at[count++] = temp;
			if(temp.left != null) {
				quene.add(temp.left);
			}
			if(temp.right != null) {
				quene.add(temp.right);
			}
		}
	}
	
	//层次遍历
	public void levelOrder(){
		for(int i=0; i<at.length; i++) {
			System.out.print(at[i].data + " ");
		}
	}
	
	public void preOrder() {
		this.preOrder(0);
	}
	//前序遍历
	public void preOrder(int n) {
		if(this.at == null || this.at.length == 0) {
			return ;
		}
		System.out.print(at[n].data + " ");
		if((2 * n + 1) < at.length) {
			preOrder(2 * n + 1);
		}
		if((2 * n + 2) < at.length) {
			preOrder(2 * n + 2);
		}
	}
	public void inOrder() {
		this.inOrder(0);
	}
	//中序遍历
	public void inOrder(int n) {
		if(this.at == null || this.at.length == 0) {
			return ;
		}
		if((2 * n + 1) < at.length) {
			inOrder(2 * n + 1);
		}
		System.out.print(at[n].data + " ");
		if((2 * n + 2) < at.length) {
			inOrder(2 * n + 2);
		}
	}
	public void postOrder() {
		this.postOrder(0);
	}
	//后序遍历
	public void postOrder(int n) {
		if(this.at == null || this.at.length == 0) {
			return ;
		}
		if((2 * n + 1) < at.length) {
			inOrder(2 * n + 1);
		}
		
		if((2 * n + 2) < at.length) {
			inOrder(2 * n + 2);
		}
		System.out.print(at[n].data + " ");
	}
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值