LeetCode 111. Minimum Depth of Binary Tree

题目描述

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its minimum depth = 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 == NULL){
            return 0;
        }
        
        int minlevel = 1;
        int current = 1;
        int next = 0;
        deque<TreeNode *> que;
        que.push_back(root);
        TreeNode *temp;
        
        while(!que.empty()){
            temp = que.front();
            que.pop_front();
            current -= 1;
            
            if(temp->left==NULL && temp->right == NULL){
                return minlevel;
            }
            
            if(temp->left != NULL){
                que.push_back(temp->left);
                next += 1;
            }
            if(temp->right != NULL){
                que.push_back(temp->right);
                next += 1;
            }
            
            if(current == 0){
                current = next;
                next = 0;
                minlevel += 1;
            }
        }
        return 0; // 这句话永远也不会执行的
    }
};

总结展望

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容