【问题标题】:How to find the height of the left and right subtree in C#C#中如何求左右子树的高度
【发布时间】:2013-02-13 03:26:09
【问题描述】:

如何找到左右两边的子树高度,我在下面的链接中使用了这个代码 C# BST

任何帮助将不胜感激。

亲切的问候

【问题讨论】:

  • 二叉树的高度是多少?最大高度?最小高度?
  • 这是检查它是否高度平衡。因为我是编码新手,所以我不知道如何构建它。我需要知道左子树的最大高度和右子树的最大高度
  • 正在寻找该函数以使用上面的源查找高度。

标签: c# binary-tree binary-search-tree subtree


【解决方案1】:

好吧,如果它是 BST 的正确实现,那么它们应该是平衡的。

但是为了测试它,这里有一个简单的递归实现。

public int TreeDepth( TreeNode<T> tree, int depth = 0 )
{
    int leftDepth = tree.Left != null 
        ? TreeDepth( tree.Left, depth + 1 ) 
        : depth;
    int rightDepth = tree.Right != null 
        ? TreeDepth( tree.Right, depth + 1 ) 
        : depth;
    return leftDepth >= rightDepth 
        ? leftDepth 
        : rightDepth;
}

【讨论】:

  • 实现正确,我检查了测试代码。我想知道如何调用 TreeDepth 以及要传递哪些参数。感谢您的帮助@Kaerber
  • 你只需将你想要测量的树传递给它,就像这样: var depth = TreeDepth( root );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
相关资源
最近更新 更多