[英]What is the time complexity of the best case to insert a new node into a minimum-level BST with n nodes?
I am learning about algo complexity and calculating time complexity. 我正在学习算法复杂度并计算时间复杂度。 the question is
问题是
What is the time complexity of the best case to insert a new node into a minimum-level BST with n nodes? 将新节点插入具有n个节点的最低级别的BST的最佳情况的时间复杂度是多少? Explain.
说明。 (Hint: You may draw a diagram as part of your solution.)
(提示:您可以绘制图表作为解决方案的一部分。)
Can you please explain in details how you would solve this question and similar questions? 您能否详细说明如何解决此问题和类似问题?
my attempt: 我的尝试:
for time complexity we have 2 questions, how many times and what does it cost. 对于时间复杂度,我们有2个问题,多少次,花费多少。
How many times: there will be one element to check so => O(1) how much does it cost? 多少次:将检查一个元素,所以=> O(1)花费多少? how many times?
多少次?
now I am stuck here (pretty early), I am assuming that since its a tree, there will be n/2 elements after the first comparison and it keeps splitting into half. 现在我被困在这里(很早),我假设由于它是一棵树,因此在第一次比较之后将有n / 2个元素,并且它会一直分裂为一半。
Consider the following minimum-height BST (any binary tree with 8
nodes has at least 4 levels, thus it has the minimum height). 请考虑以下最小高度BST(具有
8
节点的任何二叉树至少具有4个级别,因此它具有最小高度)。
8
/
4
/ \
2 6
/ \ / \
1 3 5 7
Now let's say you insert the value 9
, it will go straight to the right side of the root. 现在,假设您插入值
9
,它将直接进入根的右侧。
To generalize this example: a BST which has a right child or left child which are complete trees- is a minimum height BST. 概括此示例:具有完整树的右孩子或左孩子的BST是最小高度BST。 If the other side is empty, any value that you'll insert which will be greater\\lesser to the node will be added directly to the root's right\\left child.
如果另一侧为空,则您要插入的任何值(该值比该节点大/小)将直接添加到根的right / left子级。 in this case the insert will take
O(1)
time. 在这种情况下,插入将花费
O(1)
时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.