[英]Node with minimum value in a Binary Search Tree
I would like to find the most efficent way to check the node with minimum value in a Binary Search Tree.我想找到最有效的方法来检查二叉搜索树中具有最小值的节点。 I'm not thinking to do it in a certain programming language right now, I would like just to think the most efficent algorithm.
我现在不想用某种编程语言来做,我只想考虑最有效的算法。
What do you think about this:你怎么看待这件事:
procedure minBST(t)
if (t = NULL) then return;
if (t -> left = NULL) then return t -> inf;
*// if the left node is null, then in a BST the smallest value will be the root*
if (t -> left != NULL) then ....
*// I need to dig more in the left side until I get the last left node*
My question is how should I dig deeper until I get the last left node.我的问题是我应该如何深入挖掘,直到获得最后一个左节点。 Also I tried to explain the steps.
我也试图解释这些步骤。 Do you think that is the best way to do it?
你认为这是最好的方法吗?
If you have a proper BST you can continue going down the left child:如果你有一个合适的 BST,你可以继续沿着左边的孩子走:
10
/ \
5 12
/ \ / \
1 6 11 14
If a node does not have a left child (Null) you know the node you're currently in has the minimum value.如果一个节点没有左孩子(Null),你就知道你当前所在的节点具有最小值。 The easiest approach is via recursion:
最简单的方法是通过递归:
int minBST(TreeNode node)
{
if (node->left == Null)
return node->value;
else
return minBST(node->left);
}
To start the search simply call the function above with the root as node parameter.要开始搜索,只需使用根作为节点参数调用上面的函数。 The tree above will have a code path as follows:
上面的树将具有如下代码路径:
If your tree contains n nodes and is balanced (equal depth everywhere) this will take O(log_2 n) operations and is the fastest approach without additional bookkeeping.如果您的树包含 n 个节点并且是平衡的(处处深度相等),这将需要 O(log_2 n) 次操作,并且是无需额外簿记的最快方法。 The fact that the tree is balanced is important to get the best performance, if you want to maintain your tree balanced have a look at red-black trees.
树是平衡的这一事实对于获得最佳性能很重要,如果您想保持树平衡,请查看红黑树。
The following code should do the job:以下代码应该可以完成这项工作:
node* FindMin(node* n)
{
if(n == NULL)
return NULL;
if(n->left == NULL)
return n;
while(n->left != NULL)
{
n = n->left;
}
return n;
}
The complexity is O(log(n)), that the best you can get assuming the tree is balanced.复杂度是 O(log(n)),假设树是平衡的,你可以得到最好的。
public int MinValue(TreeNode root)
{
if (root == null)
{
return -1;
}
TreeNode node = root;
while (node.Left != null)
{
node = node.Left;
}
return node.Value;
}
https://codestandard.net/articles/min-value-binary-search-tree https://codestandard.net/articles/min-value-binary-search-tree
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.