如何求出树的最小深度

How would you find the min depth of a tree?

本文关键字:深度 何求出      更新时间:2023-10-16

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

这里需要注意的一点是,当您执行递归时,您正在使用流程执行堆栈。这通常有操作系统设置的一些限制。因此,每次递归时,进程状态都被压入这个堆栈。所以在某个点发生了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,它可以在常数时间内给出最小值。

UPDATE:既然你把问题改成min-depth

MIN-DEPTH

#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:代码是手写的,可能有语法错误,但我相信逻辑是好的…

我知道这是很久以前的问题了,但对于那些无意中发现这里并不想使用递归的人,这里是我的伪(我为没有提供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)

时间复杂度是线性的