• leetcode1Minimum 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.
    示例1

    输入

    复制
    {1,2,3,4,5}

    输出

    复制
    2
    

    /**
     * struct TreeNode {
     *    int val;
     *    struct TreeNode *left;
     *    struct TreeNode *right;
     * };
     */

    class Solution {
    public:
        /**
         *
         * @param root TreeNode类
         * @return int整型
         */
        int run(TreeNode* root) {
            // write code here
            if (root==nullptr) return 0;
            if (root->left == nullptr)
            {
                return run(root->right) +1;
                
            }
            if (root->right == nullptr)
            {
                return run(root->left)+1;
                
            }
            int leftDepth=run(root->left);
            int rightDepth=run(root->right);
            return (leftDepth <rightDepth) ?(leftDepth+1):(rightDepth+1);
        }
        
    };

    /**
     * struct TreeNode {
     *    int val;
     *    struct TreeNode *left;
     *    struct TreeNode *right;
     * };
     */

    class Solution {
    public:
        typedef TreeNode *tree;
        /**
         *
         * @param root TreeNode类
         * @return int整型
         */
        int run(TreeNode* root) {
            // write code here
            if (!root) return 0;
            queue <tree> qu;
            tree last,now;
            int level,size;
            last=now=root;
            level=1;qu.push(root);
            while (qu.size()){
                now=qu.front();
                qu.pop();
                size=qu.size();
                if (now->left) qu.push(now->left);
                if (now->right) qu.push(now->right);
                if (qu.size()-size==0) break;
                if (last==now){
                    level++;
                    if (qu.size()) last=qu.back();
                    
                }
            }
            return level;
            
        }
    };

  • 相关阅读:
    使用Dockerfile构建镜像并push到私有仓库
    docker registry-v2 搭建私有仓库
    spring-cloud 学习四 服务网关
    spring-cloud 学习三 服务提供者
    TortoiseSVN安装和使用
    SG-UAP常用注解介绍
    weblogic漏洞
    开发工具历史版本
    Android Studio 打包生成apk
    weblogic unable to get file lock问题
  • 原文地址:https://www.cnblogs.com/hrnn/p/13438306.html
Copyright © 2020-2023  润新知