您的位置:首页 > 其它

[LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)

2016-01-12 20:56 525 查看
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.

本题就是求解二叉树的深度: 
递归解法: 
(1)如果二叉树为空,二叉树的深度为0 
(2)如果二叉树不为空,二叉树的深度 = min(左子树深度, 右子树深度) + 1

(3)需要注意的是斜二叉树情况,当节点的左子树深度为0或者节点的右子树深度为0.

采用DFS深度优先遍历,我们只要叶子节点。

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

int minDepth(TreeNode *root)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (root == NULL)
return 0;

if (root->left == NULL && root->right == NULL)
return 1;

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

if (leftDepth == 0)
return rightDepth + 1;
else if (rightDepth == 0)
return leftDepth + 1;
else
return leftDepth < rightDepth ? (leftDepth +1 ) : (rightDepth +1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode