如何求出树的最小深度
How would you find the min depth of a tree?
我知道如何使用堆栈和有序遍历找到树的最大深度,但我不知道如何使用堆栈或队列而不是递归调用找到树的最小深度(不一定是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)
时间复杂度是线性的
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 给定两个偶数,求出它们之间所有偶数的平方和
- OpenGL - 阴影贴图/深度贴图给出奇怪的结果
- 在给定某些约束的情况下,求出元素之间的最大距离
- 给定一个N个数的数组,求出所有长度的序列在R范围内的个数
- 如何在C++中求出二维int数组的大小
- 用C++对作为数据给出的任意函数进行有效求值
- 如何递归地求出数组中一定数量的数字
- C++ 和 Java 之间的表达式求值顺序有何不同
- 在 N 个元素的数组中求出"P"元素的最小和,以便一起选择不超过"k"个连续元素
- C++算法优化:从N个元素中求出K组合
- 求出给定范围内的完美正方形的数量
- 从一组数据中求出奇数的最小最大值和偶数的和
- 如果语句不求值为false?程序给出奇怪的输出.为什么
- 如何求出树的最小深度
- 在cpp中求出图像中物体的尺寸
- 给定一个排序数组和一个参数 k,求出线性时间内大于或等于 k 的两个数字的总和