zoukankan      html  css  js  c++  java
  • 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;
            
        }
    };

  • 相关阅读:
    Nancy 寄宿IIS
    原子操作
    CSRF跨站请求伪造
    CORS跨域
    C# 运算符
    Mysql 函数
    Mongodb for .Net Core 驱动的应用
    Mongodb for .Net Core 封装类库
    制作项目模板
    压缩图片
  • 原文地址:https://www.cnblogs.com/hrnn/p/13438306.html
Copyright © 2011-2022 走看看