A simple Binary Search Tree written in C# and the case at the bottom

2023-05-16

Introduction

In Computer Science, a binary tree is a hierarchical structure of nodes, each node referencing at most to two child nodes. Every binary tree has a root from which the first two child nodes originate. If a node has no children, then such nodes are usually termed leaves, and mark the extent of the tree structure.

A particular kind of binary tree, called the binary search tree, is very useful for storing data for rapid access, storage, and deletion. Data in a binary search tree are stored in tree nodes, and must have associated with them an ordinal value or key; these keys are used to structure the tree such that the value of a left child node is less than that of the parent node, and the value of a right child node is greater than that of the parent node. Sometimes, the key and datum are one and the same. Typical key values include simple integers or strings, the actual data for the key will depend on the application. In this article, I describe a binary search tree that stores string/double pairs. That is, the key is the string value and the data associated with the key is a double value. Developers can search the tree using string values.

Sample Image - maximum width is 600 pixels

Background

There are a number of basic operations one can apply to a binary search tree, the most obvious include, insertion, searching, and deletion.

To insert a new node into a tree, the following method can be used. We first start at the root of the tree, and compare the ordinal value of the root to the ordinal value of the node to be inserted. If the ordinal values are identical, then we have a duplicate and we return to the caller indicating so. If the ordinal value is less than the root, then we follow the left branch of the root, else we follow the right branch. We now start the comparison again but at the branch we took, comparing the ordinal value of the child with the node to be inserted. Traversal of the tree continues in this manner until we reach a left or right node which is empty and we can go no further. At this point, we insert the new node into this empty location. Note that new nodes are always inserted as leaves into the tree, and strictly speaking, nodes are thus appended rather than inserted.

Searching a binary search tree is almost identical to inserting a new node except that we stop the traversal when we find the node we're looking for (during an insertion, this would indicate a duplicate node in the tree). If the node is not located, then we report this to the caller.

Both insertion and searching are naturally recursive and are, arguably, easier to understand when considered in terms of their unit operation. A basic recursive search algorithm will look like:

 Collapse  |  Copy Code

 
 
node search (node, key) {
if node is null then return null;
if node.key = key then
if key < node then
return node return search (node.left, key); else return search (node.right, key);

In the source code provided with this article, insertion is implemented recursively, while searching uses an iterative approach.

Deletion is a little bit more complicated but boils down to three rules. The three rules refer to deleting nodes without any children, nodes with one child, and nodes with two children. If a node has no children, then the node is simply deleted. If the node has one child, then the node is deleted and the child node is brought forward to link to the parent. The complication occurs when a node has two children. However, even here, the rules are straightforward when stated. To delete a node with two children, the next ordinal node (called the successive node) on the right branch is used to replaced the deleted node. The successive node is then deleted. The successive node will always be the left most node on the right branch (likewise, the predecessor node will be the right most node on the left branch). The figure below illustrates the deletion rules.

Deletion rules

A common alternative to using binary search tree is to use Hash tables. Hash tables have better search and insertion performance metrics. In theory, the time it takes to insert or search for an item in a Hash table is independent of the number of data items stored. In contrast, a binary search tree scales with log (N) where N is the number of data items (still far better than a linear search). The .NET libraries contain explicit support for Hash tables.

Balanced Trees

The time taken to insert or search for a specific item in a tree will be affected by a tree's depth. Deep trees take longer to search, and the insertion order into a tree can affect a tree's shape. A random insertion order will generally produce a more bushy and hence shallower tree compared to an ordered insert. Bushy trees are often called balanced trees, and although not implemented here, balancing a tree is a highly desirable feature for a binary search tree implementation. Certain algorithms such as the red-black tree will auto-balance as the tree is constructed (see Red/Black tree animation). The figure below shows three trees generated by three identical data sets but inserted in a different order. The first is the most balanced and hence the most shallow of the three examples.

Implementing the search and insertion methods using a recursive approach has the potential to yield poor performance, particularly when the trees are unbalanced.

Using the Code

Using the source code provided with this article is very easy. The following code illustrates the instantiation of a new binary tree, the insertion of data into the tree, and subsequent retrieval. The method insert() is used to insert new data, and the method findSymbol() is used to locate and retrieve data. If findSymbol() fails to locate the data item, it returns null. When successful, findSymbol() returns a TTreeNode object which has two properties, nameand value. The following code illustrates how to use the binary search tree. The class name of the binary tree isTBinarySTree, and the individual nodes have class type TTreeNode.

 Collapse  |  Copy Code

 
 
// Create a new binary tree
bt = new TBinarySTree();
// Insert data
bt.insert ( " Canis Minoris" , 5 . 37 );
bt.insert ( " Gamma Cancri" , 4 . 66 );
bt.insert ( " Phi Centauri" , 3 . 83 );
bt.insert ( " Kappa Tauri" , 4 . 21 );
// Retrieve data
TTreeNode symbol = bt.findSymbol ( " Phi Centauri" );
if (symbol != null )
Console.WriteLine ( " Star {1} has magnitude = {0}" , symbol.name, symbol.value);

Other methods of interest include:

 Collapse  |  Copy Code

 
 
bt.clear();
bt.count();

count returns the number of nodes in the tree.

 Collapse  |  Copy Code

bt.delete (key);  

delete will delete the node with the given key. If the method fails to locate the node, the method throws a simple exception.

The source code is licensed under the BSD license. The source should compile on C# 2.0.

To use the source code, unpack the source, load the binary tree solution (binaryTree.sln) and compile the BinaryTree project. In your own project, include as a reference to BinaryTree.dll. This version was written using Visual Studio 2003.


http://www.codeproject.com/Articles/18976/A-simple-Binary-Search-Tree-written-in-C


C# – Tree Sort – In-order traversal of a binary search tree

February 16, 2012

A tree sort is a sort algorithm that builds a binary search tree from the keys to be sorted, and then traverses the tree (in-order) so that the keys come out in sorted order. Its typical use is when sorting the elements of a stream from a file. Several other sorts would have to load the elements to a temporary data structure, whereas in a tree sort the act of loading the input into a data structure is sorting it.

Adding one item to a binary search tree is on average an O(log(n)) process, so adding n items is an O(n log(n)) process, making Tree Sort a so-called, ‘fast sort’. But adding an item to an unbalanced binary tree needs O(n) time in the worst-case, when the tree resembles a linked list (degenerate tree), causing a worst case of O(n2) for this sorting algorithm. The worst case scenario then is triggered by handing a Tree Sort algorithm an already sorted set. This would make the time needed to insert all elements into the binary tree O(n2). The dominant process in the Tree Sort algorithm is the “insertion” into the binary tree, assuming that the time needed for retrieval is O(n).
The worst-case behaviour can be improved upon by using a self-balancing binary search tree. Using such a tree, the algorithm has an O(n log(n)) worst-case performance, thus being degree-optimal. – Wikipedia

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Collections.Generic;
using System.Text;
 
namespace TreeSort
{
     class Node
     {
         public int item;
         public Node leftChild;
         public Node rightChild;
         public void displayNode()
         {
             Console.Write( "[" );
             Console.Write(item);
             Console.Write( "]" );
         }
     }
     class Tree
     {
         public Node root;
         public Tree()
         { root = null ; }
         public Node ReturnRoot()
         {
             return root;
         }
         public void Insert( int id)
         {
             Node newNode = new Node();
             newNode.item = id;
             if (root == null )
                 root = newNode;
             else
             {
                 Node current = root;
                 Node parent;
                 while ( true )
                 {
                     parent = current;
                     if (id < current.item)
                     {
                         current = current.leftChild;
                         if (current == null )
                         {
                             parent.leftChild = newNode;
                             return ;
                         }
                     }
                     else
                     {
                         current = current.rightChild;
                         if (current == null )
                         {
                             parent.rightChild = newNode;
                             return ;
                         }
                     }
                 }
             }
         }
         public void Preorder(Node Root)
         {
             if (Root != null )
             {
                 Console.Write(Root.item + " " );
                 Preorder(Root.leftChild);
                 Preorder(Root.rightChild);
             }
         }
         public void Inorder(Node Root)
         {
             if (Root != null )
             {
                 Inorder(Root.leftChild);
                 Console.Write(Root.item + " " );
                 Inorder(Root.rightChild);
             }
         }
         public void Postorder(Node Root)
         {
             if (Root != null )
             {
                 Postorder(Root.leftChild);
                 Postorder(Root.rightChild);
                 Console.Write(Root.item + " " );
             }
         }
     }
     class Program
     {
         static void Main(string[] args)
         {
             Tree theTree = new Tree();
             theTree.Insert( 42 );
             theTree.Insert( 25 );
             theTree.Insert( 65 );
             theTree.Insert( 12 );
             theTree.Insert( 37 );
             theTree.Insert( 13 );
             theTree.Insert( 30 );
             theTree.Insert( 43 );
             theTree.Insert( 87 );
             theTree.Insert( 99 );
             theTree.Insert( 9 );
 
             Console.WriteLine( "Inorder traversal resulting Tree Sort" );
             theTree.Inorder(theTree.ReturnRoot());
             Console.WriteLine( " " );
 
             Console.WriteLine();
             Console.WriteLine( "Preorder traversal" );
             theTree.Preorder(theTree.ReturnRoot());
             Console.WriteLine( " " );
 
             Console.WriteLine();
             Console.WriteLine( "Postorder traversal" );
             theTree.Postorder(theTree.ReturnRoot());
             Console.WriteLine( " " );
 
             Console.ReadLine();
         }
     }
}

OUTPUT:

About these ads

http://www.codeproject.com/Articles/18976/A-simple-Binary-Search-Tree-written-in-C

http://chinmaylokesh.wordpress.com/2012/02/16/tree-sort-in-order-traversal-of-a-binary-search-tree/


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

A simple Binary Search Tree written in C# and the case at the bottom 的相关文章

  • 在Windows中比较2个二进制文件的工具[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我需要一个工具来比较两个二进制文件 文件相当大 我在互联网上找到的一些免费软件或试用工具不方便用于大文件
  • SOLR - 过滤器查询中的正则表达式

    我想在 fq 中实现 Regex 但以前从未实现过 我的属性中有以下值 字段类型为 小写 Prop company1 city1 state1 country1 高级分析化学家 芝加哥 我想根据正则表达式过滤结果 正则表达式应该与上面的内容
  • 在应用程序中搜索对象的设计模式

    需要一些有关设计模式的帮助 我正在创建一个应用程序 该应用程序在存储在单独表中的数据库中的对象上具有不同类型 例如 我有 5 种对象 A B C D E 我在数据库中有 5 个不同的表来存储每个对象 现在 我想在我的应用程序中实现搜索功能
  • Java hibernate/jpa 如何创建自相关的动态通用实体

    我想使用 JPA hibernate 创建动态和通用的超类 它将针对每个层次结构模型进行扩展 例如 角色 页面 目录 部门 权限 树 我想使用递归和java反射来创建这个对象动态树 它应该看起来像这样 该实体应该引用自身实体 我希望它是完全
  • 将二进制文件转换为图像

    我需要找到一种将二进制文件转换为图像的快速方法 二进制文件由 N 个NN 矩阵 我想将 0 与一种颜色关联 将 1 与另一种颜色关联 我需要对超过 1000 个二进制文件执行此操作 如果可能的话 我想避免使用 MatLab 有没有任何工具
  • 如何实现 IFilter 来索引重量级格式?

    我需要为 Microsoft Search Server 2008 开发一个 IFilter 它执行长时间的计算来提取文本 从一个文件中提取文本可能需要 5 秒到 12 小时 我如何设计这样的 IFilter 以便守护进程不会在超时时重置它
  • 自定义 Tridion 搜索索引处理程序:页面 url 的自定义字段与标准字段?

    我正在研究 SDL Tridion 2011 GA 的自定义搜索索引处理程序 我得到了一些工作 使用Arjen 提供的非常有用的信息 http 80000ft blogspot nl 2012 08 search indexing hand
  • Unity InputField OnValueChanged事件显示InputField.text少一个字符

    我有一个InputField我用它作为搜索栏 我无法自动搜索OnValueChanged因为最初 文本字段将是 现在如果我输入任何字符a the inputField text还是 代替a因此 在添加下一个字符之前不会进行搜索 有没有办法在
  • 知识树中的段错误

    我正在用 c 实现一个可以从文件中读取的知识树 我的 newStr 函数出现段错误 我无法用这个问题测试我的其余代码 我对 c 没有太多经验 任何帮助将不胜感激 我的 c 文件 包括 包括 include 动物 h 包括 包括 return
  • 使用 sunspot/solr 搜索多个模型

    我已经能够成功地实现基本的全文搜索 但是当我尝试使用范围 with statements 时 任何涉及多对多关系模型的查询似乎都不适合我 我知道相关行位于数据库中 因为我的 sql 语句确实返回了数据 然而 太阳黑子查询不会返回任何结果 我
  • 生成 xcframework 库时 xcodebuild 错误“不支持具有多个平台的二进制文件”

    我正在尝试从 MyFramework framework 文件生成 xcframework 文件 我正在运行以下命令 xcodebuild create xcframework framework MyFramework framework
  • 实时搜索错误

    我正在获取用户偏好和角色 一切正常并且数据接收正确 默认值放置在单选按钮上以突出显示用户当前拥有的选项 我正在使用 Antd Design Table 组件 问题 当我将用户首选项更改为打印文档时 它确实通过数据库的状态成功更改了它 但是现
  • 如何用php将文件内容转换为字节数组

    我想用PHP将上传的文件保存 插入 到数据库中 数据库字段的类型是varbinary 最后 我想要获得 VarBinary 输出 的内容 就像在 C 中读取文件然后将其存储在字节数组中并将数组插入到 VarBinary 中一样 我与数据库的
  • 是否存在 UTF-8 编码中未使用的字节?

    据我了解 UTF 8 是 ASCII 的超集 因此包括不用于表示可打印字符的控制字符 我的问题是 是否有任何字节 256 个不同的字节 未被 UTF 8 编码使用 我想知道你是否可以转换 编码UTF 8 文本转二进制 这是我的思考过程 我不
  • 如何使用 d3.v4 中的 JSON 数据创建树布局 - 不使用 stratify()

    我正在尝试将一些 d3 代码从 v3 更新到版本 4 我有一个使用 JSON 数据的树形图 d3 v4 示例展示了如何使用 stratify 将表格数据 例如flare csv 转换为分层数据https bl ocks org mbosto
  • 测试由于浮点限制而导致的舍入误差

    我最近了解到浮点的主要限制之一 事实上 某些数字无法以二进制正确表示 因此可能给出的答案对于您的目的来说不够准确 知道round 2 675 2 and round 2 665 2 两者相等2 67我尝试编写一些代码来给出具有此属性的数字列
  • 如何使用KDTrees实现最近邻搜索?

    所以 我正在实施一个KD Tree http en wikipedia org wiki Kd tree进行最近邻搜索 我已经构建了树部分 但我认为我没有完全理解搜索部分 关于遍历树来搜索邻居 维基百科文章如下 Starting with
  • 二进制浮点加法算法

    我试图理解二进制级别的 IEEE 754 浮点加法 我遵循了一些在网上找到的示例算法 并且大量测试用例与经过验证的软件实现相匹配 我的算法目前只处理正数 但是 我没有得到与此测试用例的匹配 0000100011110011011001001
  • 反转二进制网络

    如何反转二元方程 以便找到哪些输入将产生给定的输出 Example Inputs i0 through i8 Outputs o0 through o8 Operators XOR AND 二元方程 1 i0 1 i1 0 i2 1 i3
  • 从 XML 构建树结构的速度很慢

    我正在将 XML 文档解析为我自己的结构 但对于大型输入来说构建它非常慢 是否有更好的方法来做到这一点 public static DomTree

随机推荐

  • 【总结】hadoop 磁盘满导致集群宕机排查解决

    hadoop 集群因磁盘满了 xff0c 导致服务挂掉 xff0c 甚至有机器宕机 当机器重启后 xff0c 启动nameNode 和 journalNode 有报错 1 启动 Namenode 错误信息 2023 03 27 10 23
  • 【总结】Linux vim编辑文件中文乱码cat正常(亲测有效)

    最近为了测系统的兼容性 xff0c 公司运维装了一台统信UOS arm 64的系统 xff0c 在该操作系统上部署时 xff0c 发现vim 编辑文件中文乱码 xff0c 但是使用cat 查看文件 xff0c 却是正常 网上搜索了一番 xf
  • 【总结】Springboot 从2.0.0升级至2.3.12版本hive使用报错问题解决

    背景 公司springboot 版本终于从老古董2 0 0 release 升到2 3 12版本了 xff0c 应用启动 系统登陆都正常 xff0c 但在回归验证hive时 xff0c spark sql 操作hive相关的功能却用不了 经
  • PCB封装尺寸-0402-0603-0805

    封装尺寸与封装的对应关系 封装尺寸功率电阻耐压值 V0201 1 20W2504021 0mmx0 5mm 1 16W5006031 6mmx0 8mm 1 10W5008052 0mmx1 2mm 1 8W15012063 2mmx1 6
  • SpringCloud五大核心组件使用方法

    目录 SpringCloud各组件简单介绍EurekaFeignRibbonHystrixzuul SpringCloud各组件使用方法前提准备Eureka入门案例1 新建Module2 修改pom文件3 创建 96 application
  • java变量的定义

    JAVA数据类型 对于整型数据 xff0c 通常情况下使用int类型 但是如果表示极大的数据 xff0c 就需要long类型了 xff0c byte和short类型主要用于特定的应用场合 xff0c 例如 xff1a 底层的文件处理或者需要
  • java数据类型转换(强制转换)

    数据类型的转换 xff0c 分为自动转换和强制转换 自动转换是程序在执行过程中 无声 进行的转换 xff0c 不需要提前声明 xff0c 一般是从位数低的类型向位数高的类型转换 xff1b 强制转换则必须在代码中声明 xff0c 转换顺序不
  • 斗鱼直播与熊猫直播竞品分析

    引言 xff1a 目前国内直播平台虽然十分火爆 xff0c 但是直播的市场尚未成熟 xff0c 斗鱼等其他直播平台在利用自己用户的基础一直处在直播平台的主流市场 xff0c 而新晋直播平台开始大肆的宣传和吸引用户 xff0c 最终直播这块市
  • 知乎产品分析|知识社区何去何从

    一 引言 2017 年 2 月 xff0c 知乎月独立用户设备数再次回升 xff0c 相比 1 月上涨了 11 2 xff0c 达到了 1109 万台 1 1 目的 通过对知乎这款产品的分析 xff0c 锻炼自己的思维能力 xff0c 深化
  • 我的vimrc配置文件

    34 vundle begin set nocompatible 34 与vi不一致 filetype off filetype plugin on 34 检测插件 set rtp 43 61 vim bundle vundle 34 载入
  • 以CSDN为例解释尼尔森十大交互原则

    一 状态可见原则 用户在网页上的任何操作 xff0c 不论是单击 滚动还是按下键盘 xff0c 页面应即时给出反馈 即时 是指 xff0c 页面响应时间小于用户能忍受的等待时间 举例 xff1a CSDN上文章底部都会有一个 喜欢 按钮 x
  • 游戏化思维——核心驱动力

    游戏是一个令人着迷 xff0c 并且能够让人沉迷于此的东西 xff0c 而游戏之所以如此迷人 xff0c 不但是游戏的制作精良和剧情引人入胜 除此之外还有些其他原因 xff0c 激励人民玩游戏的原因是 xff1a 游戏能够触及到人性的核心驱
  • 从产品设计到用户设计

    从产品设计到用户设计 一说起产品设计 xff0c 人们往往想到两个方面 感官方面 功能方面 感官方面 xff1a 精心设计的产品能够给用户带来赏心悦目的感觉 xff0c 当然极大部分是属于触感方面 xff08 嗅觉和味觉因为局限问题无法在产
  • 为体验设计——使用第一

    产品设计和用户体验设计有什么不同呢 xff1f 每个产品都是以用户是人类为前提而设计出来的 xff0c 而产品的每一次使用 xff0c 都会产生相应的体验 用户体验设计并完全不等同于产品设计 但是对于一个简单的情况下 xff0c 创建一个良
  • 用户体验和网站

    用户体验对于所有的产品和服务来讲 xff0c 都是至关重要的 现在讨论一种特殊产品的用户体验 xff1a 网站 xff08 这里的 网站 一词包括以内容为主的网站产品和以交互为主的网站应用 xff09 在网站上 xff0c 用户体验比任何一
  • .net C# 堆 栈 垃圾回收 GC

    NET C NET C NET C NET C NET C NET C NET C 栈 堆 垃圾回收 GC 1 尽管在 NET framework下我们并不需要担心内存管理和垃圾回收 Garbage Collection xff0c 但是我
  • 值类型总是分配在栈上吗?

    不是 xff0c 比如下面三种情况 xff1a 1 引用类型内部的变量 xff0c 即使是值类型 xff0c 也会随同引用类型的实例一起被分配在堆上 2 对于值类型的数组 xff0c 由于数组是引用类型 xff0c 数组内的值类型元素 xf
  • .NET垃圾回收机制 转

    在 NET Framework中 内存中的资源 即所有二进制信息的集合 分为 34 托管资源 34 和 34 非托管资源 34 托管资源必须接受 NET Framework的CLR 通用语言运行时 的管理 诸如内存类型安全性检查 而非托管资
  • Spring Boot 升级所遇到的坑们s 1.5.x升级到2.1.x

    下面总结从Spring Boot 1 5 15 Release版本升级到2 1 1 Release版本所遇到的问题 xff0c 因为每个项目所依赖库的多少不同 xff0c 所以有些我列出的问题可能你的产品没有遇到 xff0c 或者你的问题我
  • A simple Binary Search Tree written in C# and the case at the bottom

    Introduction In Computer Science a binary tree is a hierarchical structure of nodes each node referencing at most to two