二叉排序树创建和中序遍历(因为中序遍历刚好是有序的)
2021/8/13 23:08:44
本文主要是介绍二叉排序树创建和中序遍历(因为中序遍历刚好是有序的),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
二叉排序树介绍:
BST(Binary Sort(Search) Tree),对于二叉排序树的任何一个非叶子节点,要求左子节点的值比当前结点的值小,右子节点的值比当前节点的值大。 如果相同:则可以将该节点的放在左子节点或右子节点上
13.7.1 二叉树的创建和遍历:
package binarysorttree; public class BinarySortTreeDemo { 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.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){ root.infixOrder(); } else { System.out.println("当前二叉排序树为空,不能遍历"); return; } } } 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 infixOrder(){ if (this.left != null){ this.left.infixOrder(); } System.out.print(this.value+"\t"); if (this.right != null){ this.right.infixOrder(); } } }
这篇关于二叉排序树创建和中序遍历(因为中序遍历刚好是有序的)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求