【问题标题】:Finding BST's height non-recursively?非递归地找到 BST 的高度?
【发布时间】:2011-12-06 23:03:19
【问题描述】:

这是一种查找高度的递归方法,但我的二叉搜索树中有大量节点,我想找到树的高度并将高度分配给每个单独的子树.所以递归方法抛出stackoverflow异常,我如何非递归地做到这一点并且不使用堆栈?

private int FindHeight(TreeNode node)
    {
        if (node == null)
        {
            return -1;
        }
        else
        {
            node.Height = 1 + Math.Max(FindHeight(node.Left), FindHeight(node.Right));
            return node.Height;
        }
    }

我相信我必须使用后序遍历但没有堆栈?

【问题讨论】:

    标签: binary-search-tree


    【解决方案1】:

    我能够制作这个方法,它确实返回了正确的高度,但它为每个节点分配了深度而不是高度。

     public void FindHeight()
        {
            int maxHeight = 0;
            Queue<TreeNode> Q = new Queue<TreeNode>();
            TreeNode node;
            Q.Enqueue(Root);
            while (Q.Count != 0)
            {
                node = Q.Dequeue();
                int nodeHeight = node.Height;
                if (node.Left != null)
                {
                    node.Left.Height = nodeHeight + 1;
                    Q.Enqueue(node.Left);
                }
                if (node.Right != null)
                {
                    node.Right.Height = nodeHeight + 1;
                    Q.Enqueue(node.Right);
                }
                if (nodeHeight > maxHeight)
                {
                    maxHeight = nodeHeight;
                }
    
            }
            Console.WriteLine(maxHeight);
        }
    

    【讨论】:

      猜你喜欢
      • 2013-11-26
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2015-09-28
      • 2021-12-08
      • 2013-04-15
      • 2014-06-30
      • 1970-01-01
      相关资源
      最近更新 更多