如何在c#中找到左子树和右子树的高度

本文关键字:高度 | 更新日期: 2023-09-27 18:01:17

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

如有任何帮助,不胜感激。

亲切的问候

如何在c#中找到左子树和右子树的高度

如果这是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;
}