首页 > 其他 > 详细

LeetCode 之 111. 二叉树的最小深度

时间:2020-07-22 16:37:40      阅读:52      评论:0      收藏:0      [点我收藏+]

原题链接

思路:

递归计算每个子树的深度,返回左右子树中深度小的值;

由于题目中要求的是到最近叶子节点的深度,所以需要判断 左右子树为空的情况;

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; 
            }
        }
    }
};

 

LeetCode 之 111. 二叉树的最小深度

原文:https://www.cnblogs.com/CopyStyle/p/13360737.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!