0
点赞
收藏
分享

微信扫一扫

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.

思路分析:
求二叉树的最小深度。二叉树多用迭代。

C++示例代码:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int minDepth(TreeNode *root)
{
if (root == NULL)
{
return 0;
}

//leftDepth=0,rightDepth=0直接返回1
if (root->left == NULL && root->right == NULL)
{
return 1;
}

int leftDepth = minDepth(root->left);
int rightDepth = minDepth(root->right);

//这里leftDepth和rightDepth不可能同时为0
if (leftDepth == 0)
{
return rightDepth + 1;
}
else if (rightDepth == 0)
{
return leftDepth + 1;
}
else
{
return min(leftDepth, rightDepth) + 1;
}
}
};


举报

相关推荐

0 条评论