算法:排序二叉树的建立与遍历——Java实现

转自《Java程序员面试笔试宝典》(何昊等编著,机械工业出版社)

在排序二叉树中,左子树的数值都小于双亲结点的数值,右子树的数值都大于等于双亲结点的数值。每个子树也递归满足上述条件。

下面先给出了建立排序二叉树的算法,然后依次给出了先序、中序、后序和层序遍历二叉树的方法。

import java.util.Queue;
import java.util.LinkedList;

public class BinaryTree {
	private Node root;
	
	public BinaryTree(){
		root = null;
	}
	//向二叉排序树插入数据,小于根结点的数插入左子树,大于等于根结点的数插入右子树
	public void insert(int data){
		Node current, parent;
		Node n = new Node(data);
		if(root == null){
			root = n;
		}else{
			current = root;
			while(true){//寻找插入位置
				parent = current;
				if(data < current.data){
					current = current.left;
					if(current == null){
						parent.left = n;
						return;
					}
				}else{
					current = current.right;
					if(current == null){
						parent.right = n;
						return;
					}
				}
			}
		}
	}
	
	public void buildBinaryTree(int[] data){		
		if(data != null && data.length > 0){
			for(int i: data){
				insert(i);
			}
		}		
	}
	
	/*
	 * 中序遍历的递归实现
	 */
	public void inOrder(Node localroot){
		if(localroot != null){
			inOrder(localroot.left);
			System.out.print(localroot.data + " ");
			inOrder(localroot.right);
		}
	}
	
	public void inOrder(){
		inOrder(root);
	}
	
	//先序遍历的递归实现
	public void preOrder(Node localroot){
		if(localroot != null){
			System.out.print(localroot.data + " ");
			preOrder(localroot.left);
			preOrder(localroot.right);
		}
	}
	
	public void preOrder(){
		preOrder(root);
	}
	
	//后序遍历的递归实现
	public void postOrder(Node root){
		if(root != null){
			postOrder(root.left);
			postOrder(root.right);
			System.out.print(root.data + " ");
		}
	}
	
	public void postOrder(){
		postOrder(root);
	}
	
	//层序遍历
	public void layerTransverse(){
		if(root == null){
			return;
		}
		Queue<Node> q = new LinkedList<>();
		q.add(root);
		Node n;
		while(!q.isEmpty()){
			n = q.poll();
			System.out.print(n.data + " ");
			if(n.left != null){
				q.add(n.left);
			}
			if(n.right != null){
				q.add(n.right);
			}
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] data = {2,8,7,4,9,3,1,6,7,5};
		BinaryTree bt = new BinaryTree();
		bt.buildBinaryTree(data);
		System.out.print("in order: ");
		bt.inOrder();
		System.out.println();
		System.out.print("pre order: ");
		bt.preOrder();
		System.out.println();
		System.out.print("post order: ");
		bt.postOrder();
		System.out.println();
		System.out.print("layer transverse: ");
		bt.layerTransverse();
	}
	
}

class Node{
	int data;
	Node left , right;
	
	public Node(){}
	
	public Node(int data){
		this.data = data;
		left = null;
		right = null;
	}	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值