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.

題目思路

  • 思路一、二叉樹的層次遍歷,到某一層某個(gè)節(jié)點(diǎn)時(shí),判斷該節(jié)點(diǎn)是否左右子孩子為空,若為空則直接返回層數(shù)
/**
 * 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; // 這句話永遠(yuǎn)也不會(huì)執(zhí)行的
    }
};

總結(jié)展望

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容