非递归程序找到二叉树的最小高度

时间:2012-08-12 20:28:13

标签: binary-tree

我知道可以编写递归代码来查找最小高度。但是对于一棵非常大的树(如左侧的百万个节点和右侧的一个节点) - 这种方法并不好。所以,如果下面的代码没问题,请告诉我,它使用BFS: -

    if (root == null)
    {
        return 0;
    }

    Queue<Node> queue = new Queue<Node>();
    queue.Enqueue(root);
    int min = 0;

    while (queue.Count > 0)
    {                
        Node temp = queue.Dequeue();

        if (temp.LeftChild == null)
        {
            return ++min;
        }
        if (temp.LeftChild != null)
        {
            ++min;
            queue.Enqueue(temp.LeftChild);
        }

        if (temp.RightChild == null)
        {
            return ++min;
        }
        if (temp.RightChild != null)
        {
            ++min;
            queue.Enqueue(temp.RightChild);
        }
    }

    return 0;

对于像

这样的树
               1
              /  \
             2    3
             /
            4
            /
            6

以上返回1,(按楼层(Log(n))?

感谢。

2 个答案:

答案 0 :(得分:1)

这个想法很完美。但代码仍然可以更好。

  1. 为什么每次出列物品都会增加min?而你做了两次,它是两倍更糟:)如果你把这个变量作为节点计数器,那么它也是不正确的,因为你没有计算根元素。因此必须以其他方式调用它,而不是 min
  2. 为什么要检查孩子是否为空两次?如果声明破坏了管道,则必须将其计数最小化。
  3. 接下来是这个想法。如果其中的每个节点都有两个子节点,那么我们调用等级 full 的节点行。然后,最小高度是树中完整行的计数。它等于所有完整行+ 1中项目计数的最接近的幂指数2。 代码:

    if (root == null)
    {
        return 0;
    }
    
    Queue<Node> queue = new Queue<Node>();
    queue.Enqueue(root);
    int nodesCount = 0;
    
    while (queue.Count > 0)
    {                
        Node temp = queue.Dequeue();
    
        if (temp.LeftChild == null || temp.RightChild == null)
        {
            return Floor(Log(nodesCount + 1)/Log(2)); // It can be made much better using, for example, bitwise operations but this is not the question`s topic
        }
    
        ++nodesCount;
        queue.Enqueue(temp.LeftChild);
        queue.Enqueue(temp.RightChild);
    }
    
    return Infinity; // :)
    

答案 1 :(得分:0)

使用2个堆栈进行“Zig-zag”遍历。计算需要翻转“leftToRight”标志的次数。

相关问题