简体   繁体   中英

How would you find the min depth of a tree?

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

One thing to note here is that when you perform recursion you are using your process execution stack. This generally has some limit set by OS. So with each recursion the process state is pushed onto this stack. So at some point stackoverflow occurs.

If you end up doing a iterative version as apposed to recursive, note that the difference here is that this stack implementation is maintained by you. There is lot more work involved but stackoverflow is averted...

We could do something like the following (recursive version)-

MIN-VALUE

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

Alternatively you could use min-heap which gives you minimum value in constant time.

UPDATE: Since you changed your question to 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: Code is typed freehand, there might be syntactical errors but I believe logic is fine...

I know this was asked long time ago but for those who stumbled upon here and would rather not use recursion, here's my pseudo (My apology for not providing C++ code because I'm not verse in C++). This leverage BFS traversal.

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)

Time complexity of this one is linear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM