二叉排序树java实现

1、二叉树

二叉排序树:从任意节点开始,节点左侧节点值总比节点右侧值要小。
一个详细讲解的博客: https://www.cnblogs.com/bigsai/p/11382172.html

二叉查找树:根节点的值大于其左子树中任意一个节点的值,小于其右节点中任意一节点的值,这一规则适用于二叉查找树中的每一个节点。

二叉搜索树:每个父节点都有两个子节点(子节点可能为空),左子节点比父节点小,右子节点比父节点大。
C++实现: https://www.cnblogs.com/mcomco/p/10184033.html
一些习题:https://www.cnblogs.com/nonlinearthink/p/11042714.html

2、二叉排序树的java实现

{7,3,10,12,5,1,9}构建的二叉排序树为:
在这里插入图片描述

//实现binarysorttree;
public class BstDemo {
	public static void main(String[] args) {
		int[] arr = {7,3,10,12,5,1,9};
		BinarySortTree binarysorttree = new BinarySortTree();
		for(int i=0;i<arr.length;i++) {	//通过循环添加数组节点
			binarysorttree.add(new Node(arr[i]));
		}
		binarysorttree.perOrder();
	}
}
//二叉排序树创建
class BinarySortTree{
	private Node root;
	//添加节点的方法
	public void add(Node node) {
		if(root == null) {
			root = node;
		}else {
			root.add(node);
		}
	}
	//前序遍历
	public void perOrder() {
		if(root == null) {
			System.out.println("二叉树是空树,不能遍历");
		}else {
			root.preOrder();
		}
	}
	
}
//节点
class Node{
	int value;
	Node left;
	Node right;
	public Node(int value) {
		this.value = value;
	}
	@Override
	public String toString() {
		return "Node [value=" + value + "]";
	}
	//添加节点的方法
	public void add(Node node) {
		if(node == null) {
			return;
		}
		if(node.value < this.value ) {	//要添加的值比当前值小
			if(this.left == null) {
				this.left = node;
			}else {
				this.left.add(node);
			}
		}else {	//要添加的值比当前值大,添加到右节点
			if(this.right == null) {
				this.right = node;
			}else {
				this.right.add(node);
			}
		}
	}
	//前序遍历
	public void preOrder() {
		
		System.out.println(this.toString());
		if(this.left != null) {
			this.left.preOrder();
		}
		if(this.right != null) {
			this.right.preOrder();
		}
	}
}

前序遍历执行结果

Node [value=7]
Node [value=3]
Node [value=1]
Node [value=5]
Node [value=10]
Node [value=9]
Node [value=12]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值