Leetcode-二叉树的最小深度

25.二叉树的最小深度

题目内容:

代码及思路:

其思想与求二叉树的深度很像,但不同的是由于是计算二叉树的最小深度,因此需要注意两个点:

1.存在叶节点,那么最小深度是根节点到叶子结点的最短路径对应的深度

2.若左右子树中有一个不存在叶节点,则计算存在叶节点的深度。(因此需要判断左右子树是否为空)

/**
 * 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==nullptr)
            return 0;
        int left_depth=minDepth(root->left);
        int right_depth=minDepth(root->right);
        if(root->left==0)
            return right_depth+1;        
        if(root->right==0)
            return left_depth+1;  
        return (left_depth<right_depth)?left_depth+1:right_depth+1;
        
    }
};

猜你喜欢

转载自blog.csdn.net/larklili/article/details/89310039