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 + " ");
	}
}

你可能感兴趣的:(Java,数据结构)