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
Your answer
Expected answer
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
相关文章推荐
- The Solution to LeetCode 15 3Sum
- The Solution to LeetCode 120 Triangle
- The Solution to Leetcode 136 Single Number
- The Solution to Leetcode 268 Missing Number
- The Solution to Leetcode 110 Balanced Binary Tree
- The Solution to Leetcode 463 Island Perimeter
- The Solution to Leetcode 101 Symmetric Tree
- The Solution to Leetcode 520 Detect Capital
- The Solution to LeetCode 147 Insertion Sort List
- The Solution to Leetcode 344 Reverse String
- The Solution to Leetcode 563 Binary Tree Tilt
- The Solution to Leetcode 617 Merge Two Binary Trees
- Leetcode 8. String to Integer (atoi) The Solution of Python
- Leetcode 13. Roman to Integer The Solution of Python
- The Solution to Leetcode 541 Reverse String II
- The Solution to LeetCode 15 3Sum改进版
- Leetcode 12. Integer to Roman The Solution of Python
- The Solution to Leetcode 137 Single Number II
- The Solution to Leetcode 35 Search Insert Position
- The Solution to Leetcode 118 Pascal's Triangle