![](/img/trans.png)
[英]find the node with minimum value in a binary search tree (print that node)
[英]Node with minimum value in a Binary Search Tree
我想找到最有效的方法来检查二叉搜索树中具有最小值的节点。 我现在不想用某种编程语言来做,我只想考虑最有效的算法。
你怎么看待这件事:
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*
我的问题是我应该如何深入挖掘,直到获得最后一个左节点。 我也试图解释这些步骤。 你认为这是最好的方法吗?
如果你有一个合适的 BST,你可以继续沿着左边的孩子走:
10
/ \
5 12
/ \ / \
1 6 11 14
如果一个节点没有左孩子(Null),你就知道你当前所在的节点具有最小值。 最简单的方法是通过递归:
int minBST(TreeNode node)
{
if (node->left == Null)
return node->value;
else
return minBST(node->left);
}
要开始搜索,只需使用根作为节点参数调用上面的函数。 上面的树将具有如下代码路径:
如果您的树包含 n 个节点并且是平衡的(处处深度相等),这将需要 O(log_2 n) 次操作,并且是无需额外簿记的最快方法。 树是平衡的这一事实对于获得最佳性能很重要,如果您想保持树平衡,请查看红黑树。
以下代码应该可以完成这项工作:
node* FindMin(node* n)
{
if(n == NULL)
return NULL;
if(n->left == NULL)
return n;
while(n->left != NULL)
{
n = n->left;
}
return n;
}
复杂度是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.