二叉排序树

二叉排序树

package tree;
/**
 * 实现二叉排序树
 * @author User
 *
 */
public class BinarySortTree {
	Node root;
	
	/**
	 * 往二叉排序树中加入元素
	 * @param data
	 */
	public void add(int data) {
		Node node = new Node(data);
		Node temp = root;
		if(root == null) {
			root = node;
		}else {
			while(true) {
				// 如果严格小于就往左边放
				if(data < temp.data) {
					if(temp.left == null) {
						temp.left = node;
						return;
					}else {
						// 如果左边节点不为空,就将左边的节点变成当前节点,然后继续循环找
						temp = temp.left;
					}
				}
				// 否则也就是大于等于就往右边放
				else {
					if(temp.right == null) {
						temp.right = node;
						return;
					}else {
						temp = temp.right;
					}
				}
			}
		}
		
		
	}
	
	

	/**
	 * 中序遍历
	 * @param node
	 */
	public void middleShow(Node node) {
		if(node == null) {
			return;
		}
		middleShow(node.left);
		System.out.print(node.data + "  ");
		middleShow(node.right);
	}
	
	
	/**
	 * 前序遍历
	 * @param node
	 */
	public void frontShow(Node node) {
		if(node == null) {
			return;
		}
		System.out.print(node.data + "  ");
		frontShow(node.left);
		frontShow(node.right);
	}
	
	
	/**
	 * 后序遍历
	 * @param node
	 */
	public void backShow(Node node) {
		if(node == null) {
			return;
		}
		backShow(node.left);
		backShow(node.right);
		System.out.print(node.data + "  ");
	}
	
	
	

}


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

测试类

package tree;

public class Test {
	public static void main(String[] args) {
		int[] arr = new int[] {2,8,7,4,9,3,1,6,10,5};
		BinarySortTree tree = new BinarySortTree();
		for(int i : arr) {
			tree.add(i);
		}
		tree.middleShow(tree.root);
		System.out.println("======================");
		tree.frontShow(tree.root);
		System.out.println("======================");
		tree.backShow(tree.root);
	}
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值