您的位置:首页 > 其它

The Solution to LeetCode 111 Minimum Depth of Binary Tree

2017-03-16 16:45 387 查看
Question:

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根节点的左右子树为空,返回最小深度为1

3如果节点的左子节点为空,则遍历右子节点,并且返回深度值,按照2或4的方法进行递归。

4如果节点的右子节点为空,则遍历左子节点,并且返回深度值,按照2或3的方法进行递归。

5比较向左遍历与向右遍历的深度值,返回小的值。

Answer:

/**
* Definition for a binary tree node.
* 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;
}
else if(root->left == NULL && root->right == NULL){
return 1;
}
else if(root->left == NULL){
return minDepth(root->right) + 1;
}else if(root->right == NULL){
return minDepth(root->left) + 1;
}
else{
int l = minDepth(root->left);
int r = minDepth(root->right);
return (l < r ? l : r) + 1;
}
}
};

run code results:


Your input

[1 2 3 4 5]



Your answer

2



Expected answer

2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: