c# - 如何找出 BST 中最深的节点?

标签 c# visual-studio-2010 binary-tree binary-search-tree

private int Depth(TreeNode node)
{
    if (node == null)
    {
        return -1;
    }
    else
    {
        return 1 + Math.Max(Depth(node.LeftNode),Depth(node.RightNode));
    }
}

我写了找到最深节点的方法,但我不确定这个方法。
这是找到最深节点的正确方法吗?

最佳答案

(假设你想要得到的是树的高度,包括作为参数给出的节点)

对于空树(node == null),您将获得 -1 的深度。 对于具有 1 个节点的树,您将收到:

1 + max(-1, -1) = 0

等等,返回 0 应该可以解决问题,但总体思路没问题。

至于优化...如果您对这棵树的了解只是它是二叉树,那么这是您在不缓存节点高度的情况下可以获得的最佳结果。

至于找到最近的叶子,您可以使用 BFS算法可以有效地做到这一点,因为它会水平地发现节点,然后当你发现第一个叶子时你可以停止。

BFS 伪代码:

nodes.enqueue( tuple(node, 1)) //enqueue node with height == 1
while(nodes.count > 0)
{
  (node, h) = nodes.dequeue()
  if (node.left == null && node.right == null) return h; //If it's first leaf we've found, return it's height.

  //Enqueue our childs with their height
  if (node.left != null)
    nodes.enqueue(node.left, h+1);
  if (node.right != null)
    nodes.enqueue(node.right, h+1);
}

关于c# - 如何找出 BST 中最深的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8385001/

相关文章:

c# - 网站项目中具有相对路径的 T4 组装指令?

c++ - 在 Visual Studio 中提升测试

c - 在 "in-order tree traversal"中查找特定节点

c# - 调试 Windows 窗体应用程序

visual-studio-2010 - Test Professional 2010/Microsoft 测试管理器中的 TF30063 错误

java - Java判断二叉树是否完整

c++ - 二叉搜索树成员函数

c# - 在 Visual C# 控制台应用程序上获取多个 MySQL 查询结果

c# - 如何在 WPF 中将位图渲染到 Canvas 中?

c# - Windows 窗体 : Auto Scale Application