【问题标题】:How would you find the min depth of a tree?你如何找到一棵树的最小深度?
【发布时间】:2011-11-28 21:29:55
【问题描述】:

我知道如何使用堆栈和中序遍历找到树的最大深度,但我不知道如何使用堆栈或队列而不是递归调用来找到树的最小深度(不一定是 BST) .

【问题讨论】:

  • 你想找到标题所说的最小深度,还是问题中所说的最小值?你试过什么?你被困在哪里了?
  • @quasiverse,但使用显式堆栈不容易发生堆栈溢出。
  • 如果可以使用队列,那么广度优先搜索呢?如果您知道如何搜索最深的叶子,为什么不能使用相同的搜索来找到最浅的叶子(尽管效率低下)?

标签: c++ algorithm binary-tree


【解决方案1】:

这里要注意的一点是,当您执行递归时,您正在使用您的流程执行堆栈。这通常由操作系统设置一些限制。因此,每次递归都会将进程状态推送到此堆栈上。所以有时会发生stackoverflow。

如果您最终执行与递归相反的迭代版本,请注意这里的区别在于此堆栈实现由您维护。涉及的工作更多,但避免了 stackoverflow...

我们可以做如下的事情(递归版本)-

最小值

int min = INT_MAX;
void getMin(struct node* node)
{
     if (node == NULL)
          return;

     if(node->data < min)
          min = node->data;

     getMin(node->left);
     getMin(node->right);

     return min;
}

您也可以使用min-heap,它会在恒定时间内为您提供最小值。

更新:由于您将问题更改为最小深度

最小深度

#define min(a, b) (a) < (b) ? (a) : (b)

typedef struct Node
{
    int data;
    struct Node *left, *right;

}Node;

typedef Node * Tree;

int mindepth(Tree t)
{
    if(t == NULL || t->left == NULL || t->right == NULL)
        return 0;

    return min( 1 + mindepth(t->left), 1 +  mindepth(t->right) );
}

PS:代码是徒手输入的,可能存在语法错误,但我相信逻辑没问题...

【讨论】:

  • 仅当您将空节点视为叶节点时。但是深度通常定义为从根到最近的叶节点的距离。在您的代码中,如果一个节点有 1 个子元素,则返回 0,这意味着您将其视为叶节点。
【解决方案2】:

我知道这是很久以前问过的,但是对于那些偶然发现这里并且不想使用递归的人,这是我的伪代码(我为不提供 C++ 代码而道歉,因为我不懂 C++)。这利用了 BFS 遍历。

return 0 if root is empty

queue a tuple (that stores depth as 1 and a root node) onto a queue

while queue is not empty
   depth, node = dequeue queue
   // Just return the depth of first leaf it encounters
   if node is a leaf then : return depth
   if node has right child: queue (depth+1, node.right)
   if node has left child : queue (depth+1, node.left)

这个时间复杂度是线性的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2010-09-24
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2015-08-14
    • 2021-03-23
    相关资源
    最近更新 更多