简体   繁体   English

二叉搜索树插入方法的时间复杂度

[英]Time Complexity of a Binary Search Tree Insert method

Good day! 美好的一天!

I have a question regarding the time complexity of a binary search tree insertion method. 我对二进制搜索树插入方法的时间复杂度有疑问。 I read some of the answers regarding this but some were different from each other. 我读了一些与此有关的答案,但有些彼此不同。 Is the time complexity for a binary search tree insertion method O(log n) at average case and O(n) at worst case? 二叉搜索树插入方法的时间复杂度是否为平均情况下的O(log n)和最坏情况下的O(n)? Or is it O(n log n) for the average case and O(n^2) for the worst case? 还是一般情况下为O(n log n),最坏情况下为O(n ^ 2)? When does it become O(n log n) at average case and O(n^2) at worst case? 一般情况下什么时候变为O(n log n),最坏情况下什么时候变为O(n ^ 2)?

In avg case, is O(log n) for 1 insert operation since it consists of a test (constant time) and a recursive call (with half of the total number of nodes in the tree to visit), making the problem smaller in constant time. 在平均情况下,一次插入操作的O(log n)为O(log n),因为它包含一个测试(恒定时间)和一个递归调用(具有要访问的树中节点总数的一半),从而使问题的常数变小了时间。 Thus for n insert operations, avg case is O(nlogn). 因此,对于n次插入操作,平均大小写为O(nlogn)。 The key is that the operation requieres time proportional to the height of the tree. 关键是操作需要的时间与树的高度成正比。 In average, 1 insert operation is O(logn) but in the worst case the height is O(n) If you're doing n operations, then avg is O(nlgn) and worst O(n^2) 平均而言,1次插入操作为O(logn),但在最坏的情况下,高度为O(n)。如果要执行n次操作,则avg为O(nlgn),最差的是O(n ^ 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM