切换导航
{{systemName}}
{{ info.Title }}
{{info.Title}}
{{ menu.Title }}
{{menu.Title}}
登录
|
退出
搜索
C#二叉树查找法
作者:ych
#### 概念 二叉排序树或者是一棵空树,或者是具有下列性质的二叉树。二叉树查找需要先生成一个二叉排序树,再遍历所有节点逐一比较其值与关键字是否相同,相同则返回;若一直找不到,则返回-1。 二叉排序树或者是一棵空树,或者是具有下列性质的二叉树: >若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值; 若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值; 左、右子树也分别为二叉排序树。 二叉树查找需要先生成一个二叉排序树,再遍历所有节点逐一比较其值与关键字是否相同,相同则返回;若一直找不到,则返回-1。 #### 实例 ``` public class BSTNode { public int Key { get; set; } public int Index { get; set; } public BSTNode Left { get; set; } public BSTNode Right { get; set; } public BSTNode(int key, int index) { Key = key; Index = index; } public void Insert(int key, int index) { var tree = new BSTNode(key, index); if (tree.Key <= Key) { if (Left == null) { Left = tree; } else { Left.Insert(key, index); } } else { if (Right == null) { Right = tree; } else { Right.Insert(key, index); } } } public int Search(int key) { //找左子节点 var left = Left?.Search(key); if (left.HasValue && left.Value != -1) return left.Value; //找当前节点 if (Key == key) return Index; //找右子节点 var right = Right?.Search(key); if (right.HasValue && right.Value != -1) return right.Value; //找不到时返回-1 return -1; } } ``` #### 调用 ``` public class Program { public static void Main(string[] args) { int[] array = { 43, 69, 11, 72, 28, 21, 56, 80, 48, 94, 32, 8 }; Console.WriteLine(BinaryTreeSearch(array)); Console.ReadKey(); } public static int BinaryTreeSearch(int[] array) { var bstNode = new BSTNode(array[0], 0); for (int i = 1; i < array.Length; i++) { bstNode.Insert(array[i], i); } return bstNode.Search(80); } } ``` #### 结果 ``` 7 ``` #### 分析 在最坏的情况下二叉树查找的时间复杂度为:O(n) ,在平均情况下的时间复杂度为: O(logn) 。
相关推荐
.Net面试题
.net 10万+大数据处理方式、应用场景
单例模式的应用场景
http超文本传输协议
什么是死锁?死锁产生的原因?如何避免死锁?
B+树为什么快
MySQL索引原理
HTTP协议-HTTP3
Redis的优点
详解C#中SqlParameter的作用与用法
ElasticSearch使用场景
web技术演化
redis缓存穿透、缓存击穿、缓存雪崩原因+解决方案
消息队列使用的场景介绍
redis在项目中的使用
TiDB使用场景
面向对象
.net插入日志数据纠错
TCP三次握手和四次挥手
评论区
先去登录
版权所有:机遇屋在线 Copyright © 2021-2025 jiyuwu Co., Ltd.
鲁ICP备16042261号-1