leetcode 111. 二叉树的最小深度

题目描述:


给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最小深度  2.


思路:采用后序遍历,当前结点的深度最小深度等于左右子树较小深度加一,唯一要注意的是如果当前结点的左右子树为空时,深度应该等于非空子树深度加一。


代码:


方法一:后序遍历递归

#include<algorithm>
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL)return 0;
        int left_depth=minDepth(root->left);
        int right_depth=minDepth(root->right);
        if(left_depth&&right_depth)
            return min(left_depth,right_depth)+1;
        else
            return max(left_depth,right_depth)+1;
    }
};
方法二:层次遍历,使用队列完成
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL)return 0;
        queue<TreeNode *>q;
        q.push(root);
        int depth=0;
        while(!q.empty()){
            queue<TreeNode *>qt;
            depth++;
            while(!q.empty()){
                TreeNode * temp=q.front();
                q.pop(); 
                if(!temp->left&&!temp->right)return depth;
                if(temp->left)qt.push(temp->left);
                if(temp->right)qt.push(temp->right);
            }
            q=qt;
        }
        return depth;
    }
};
都是自己码的,顺便巩固一下层次遍历队列的使用


猜你喜欢

转载自blog.csdn.net/weixin_42130471/article/details/80333496