二叉排序树创建和遍历

二叉排序树创建和遍历

二叉排序树:BST对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前的值小,右子节点的值比当前的值大.


添加代码块

采用的递归添加的。

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

添加步骤:
1:
在这里插入图片描述2:
在这里插入图片描述3:
在这里插入图片描述4:
在这里插入图片描述5:

package mzy.tree_d;

public class BinarySortTreeTest {
	public static void main(String[] args) {
		BinarySortTree bst = new BinarySortTree();
		int[] arr = { 8, 5, 9, 11, 75, 1, 3, 29, 46 };
		for (int i = 0; i < arr.length; i++) {
			Node n = new Node(arr[i]);
			bst.add(n);
		}
		bst.infixOrder();
	}
}

//创建二叉排序树
class BinarySortTree {
	private Node root;

	// 添加节点
	public void add(Node node) {
		if (root == null) {
			root = node;
		} else {
			root.add(node);
		}
	}

	// 中序遍历
	public void infixOrder() {
		if (root == null) {
			System.out.println("此树根为空");
			return;
		}
		root.infixOrder();
	}
}
//创建Node节点
class Node {
	int value;
	Node left;
	Node right;
	public Node(int value) {
		this.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 infixOrder() {
		if (this.left != null) {
			this.left.infixOrder();
		}
		System.out.println(this);
		if (this.right != null) {
			this.right.infixOrder();
		}
	}
	// 打印遍历
	@Override
	public String toString() {
		return "Node [value=" + value + "]";
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理想艺术!马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值