您的位置:首页 > 其它

LeetCode:Minimum Depth of Binary Tree

2015-10-11 18:43 411 查看
Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

My Solution

1. 二叉树顺序遍历,在回溯时判断是否为叶子节点,若是,则判断层数是否更浅。这个和上一篇几乎一样,只是判断层数的地方由取较小者改为了取较大者。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/

#define STACK_LEN 4096
void* stack[STACK_LEN] = {0};
int eleNum = 0;
void push(void* stack[], void* elem)
{
if(eleNum < STACK_LEN)
{
stack[eleNum++] = elem;
}
}
void* pop(void* stack[])
{
return eleNum > 0 ? stack[--eleNum] : NULL;
}

int minDepth(struct TreeNode* root) {
if(NULL == root)
{
return;
}
struct TreeNode *current = root;
struct TreeNode *last = NULL;
int depth = 1;
int minDepth = INT_MAX;
while(current != NULL)
{
// 向左下降
if(current->left != NULL
&& (
last == NULL
|| last->left == current
|| last->right == current
)
&& depth < minDepth
)
{
++depth;
push(stack, current);
last = current;
current = current->left;
}
// 向右下降
else if(current->right != NULL
&& (
last == NULL
|| last->left == current
|| last->right == current
|| last == current->left
)
&& depth < minDepth
)
{
++depth;
push(stack, current);
last = current;
current = current->right;
}
// 回溯
else
{
if(current->left == NULL
&& current->right == NULL
&& depth < minDepth)
{
minDepth = depth;
}
--depth;
last = current;
current = (struct TreeNode*)pop(stack);
}
}
return minDepth;
}
2. 二叉树递归遍历。这里的思路和求最深层数基本一致,但具体代码有些不同。

求最深层数时,比较左右两子树的深度,并使用较大的深度。而求最浅层数时,不能简单比较并使用较小的深度。因为当某个节点没有左孩子但有右孩子时,左边的深度是0,一定是较小者。但这个左孩子并不存在,即该节点的左子树为空,不存在叶子节点。所以这个深度信息是无效的。当某个节点只有左孩子而没有右孩子时同理。所以在代码中要简单做一下判断。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
int minDepth(struct TreeNode* root) {
if(!root)
{
return 0;
}
if(root->left == NULL)
{
return minDepth(root->right) + 1;
}
else if(root->right == NULL)
{
return minDepth(root->left) + 1;
}
else
{
int leftDepth = minDepth(root->left) + 1;
int rightDepth = minDepth(root->right) + 1;
return leftDepth > rightDepth ? rightDepth : leftDepth;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: