一.解法
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
要点:递归,树
Python,C++,Java都用了相同的递归方法,类似104的最大深度,有个坑是[1,2]得到的结果是2,因为只有2这个节点,不能把空节点算作一个叶子节点,所以加了root.left==None和root.right==None的单独情况
二.Python实现
# 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: TreeNode) -> int:
if root==None:
return 0
if root.left==None:
return 1+self.minDepth(root.right)
if root.right==None:
return 1+self.minDepth(root.left)
return min(self.minDepth(root.left),self.minDepth(root.right))+1
三.C++实现
/**
* 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) return 0;
if(!root->right) return 1+minDepth(root->left);
if(!root->left) return 1+minDepth(root->right);
return min(minDepth(root->left),minDepth(root->right))+1;
}
};
四.java实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
if(root.right==null) return 1+minDepth(root.left);
if(root.left==null) return 1+minDepth(root.right);
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}