题目描述
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.
Note: A leaf is a node with no children.
大意就是,计算二叉树的最小深度。
思路
递归思想。不同于求二叉树最大深度(也就是二叉树的深度定义),这里要考虑几种情况。
- 左右子树都不为空
- 左子树为空,右子树不为空
- 左子树不为空,右子树为空
C++代码
// 90ms过大集合
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root!=NULL&&root->left!=NULL&&root->right!=NULL){
int l=minDepth(root->left);
int r=minDepth(root->right);
return (l<r?l:r)+1;
}else if(root!=NULL&&root->left==NULL){
return 1+minDepth(root->right);
}else if(root!=NULL&&root->right==NULL){
return 1+minDepth(root->left);
}else{
return 0;
}
}
};
Python3代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root!=None and root.left!=None and root.right!=None:
ld = self.minDepth(root.left)
rd = self.minDepth(root.right)
return 1+(ld if ld < rd else rd)
elif root!=None and root.left == None:
return 1+self.minDepth(root.right)
elif root!=None and root.right == None:
return 1+self.minDepth(root.left)
else:
return 0
文章来源:
https://blog.csdn.net/feliciafay/article/details/18399489