LeetCode:Minimum Depth of Binary Tree

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值