• [LeetCode] Minimum Depth of Binary Tree(bfs)


    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.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode *root) {
            queue<TreeNode*> q;
            if(root==NULL)
                return 0;
            q.push(root);
            q.push(NULL);//q中出现NULL表示本层结束
            return bfs(0,q);
        }
    private:
        int bfs(int depth,queue<TreeNode*> &q){
            queue<TreeNode*> temp;
            while(!q.empty()){
    
                TreeNode *p =  q.front();
                q.pop();
                if(p==NULL)//本层结束
                {
                    depth++;
                    q = temp;
                    while(!temp.empty())
                      temp.pop();
                    q.push(NULL);
                    continue;
                }
                if(p->left !=NULL)
                    temp.push(p->left);
                if(p->right != NULL)
                    temp.push(p->right);
                if(p->left==NULL && p->right==NULL)
                    return depth+1;
            }//end while
        }
    };
  • 相关阅读:
    NPIV介绍
    PowerShell随笔2_分支 选择 循环 特殊变量
    socket编程原理
    Linux查看物理CPU个数、核数、逻辑CPU个数
    Markdown 使用指南
    Linux Socket
    YoutubeAPI使用
    Youtube API数据类型
    Linux wpa_cli 调试方法
    linux网络编程
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3890419.html
Copyright © 2020-2023  润新知