这篇文章主要介绍了java中二叉排序树的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
二叉排序树:BST: (Binary Sort(Search) Tree), 对于二叉排序树的 任何一个非叶子节点,要求 左子节点的值比当前节点的值小, 右子节点的值比当前节点的值大。
特别说明: 如果有相同的值,可以将该节点放在左子节点或右子节点。
比如针对前面的数据{7, 3, 10, 12, 5, 1, 9} ,对应的二叉排序树为 :
代码实现:
package tree;
public class BinarySortTreeDemo {
public static void main(String[] args) {
int[] arr= {7,3,10,12,5,1,9,2};
BinarySortTree binarySortTree = new BinarySortTree();
for (int i = 0; i < arr.length; i++) {
binarySortTree.add(new Node(arr[i]));
}
binarySortTree.infixOrder();
}
}
//创建二叉树
class BinarySortTree{
private Node root;
public Node getRoot() {
return root;
}
public void add(Node node) {
if(root == null) {
this.root = node;//如果root为空直接让root指向node
}else {
this.root.add(node);
}
}
// 中序遍历
public void infixOrder() {
if(root!=null) {
root.infixOrder();
}else {
System.out.println("二叉树为空,不能遍历");
}
}
}
//创建结点
class Node{
private int value;
private Node left;
private 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) {//如果当前结点左子结点为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();
}
}
}
感谢你能够认真阅读完这篇文章,希望小编分享的“java中二叉排序树的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/yuchener/blog/4557414