以非递归方式查找BST的高度?

时间:2011-12-06 07:00:45

标签: binary-search-tree

这是一个用于查找高度的递归方法,但我的二叉搜索树中有非常多的节点,我想找到树的高度以及为每个子树分配高度。所以递归方法抛出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;
        }
    }

我相信我必须使用邮政订单遍历但没有堆栈?

1 个答案:

答案 0 :(得分:0)

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

 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);
    }