思路:
递归计算每个子树的深度,返回左右子树中深度小的值;
由于题目中要求的是到最近叶子节点的深度,所以需要判断 左右子树为空的情况;
python/python3:
class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root: if not root.left and root.right: return 1 + self.minDepth(root.right) elif not root.right and root.left: return 1 + self.minDepth(root.left) else: return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 else: return 0
C++:
class Solution { public: int minDepth(TreeNode* root) { if(root == NULL){ return 0; } else{ if(root->left == NULL && root->right != NULL){ return 1 + minDepth(root->right); } else if(root->right == NULL && root->left != NULL){ return 1 + minDepth(root->left); } else{ return min(minDepth(root->left), minDepth(root->right)) + 1; } } } };
原文:https://www.cnblogs.com/CopyStyle/p/13360737.html