zoukankan      html  css  js  c++  java
  • leetcode45:maximum depth of binary tree

    题目描述

    求给定二叉树的最大深度,
    最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


    示例1

    输入

    复制
    {1,2}

    输出

    复制
    2
    
    示例2

    输入

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

    class Solution {
    public:
        /**
         *
         * @param root TreeNode类
         * @return int整型
         */
        int maxDepth(TreeNode* root) {
            // write code here
            if (root==NULL){return 0;}
            queue<TreeNode*> que;
            que.push(root);
            int depth=0;
            while (!que.empty()){
                int size=que.size();
                depth++;
                for (int i=0;i<size;++i){
                    TreeNode *tmp=que.front();
                    que.pop();
                    if (tmp->left !=NULL)
                        que.push(tmp->left);
                    if (tmp->right !=NULL)
                        que.push(tmp->right);
                }
            }
            return depth;
        }
    };

  • 相关阅读:
    P2197 nim游戏
    P3942 将军令
    UVA10228 模拟退火
    关于欧拉定理的证明以及扩展欧拉定理的证明及其应用
    秒杀架构模型设计
    大型网站如何防止崩溃,解决高并发带来的问题
    序列化与反序列号
    普通常用知识汇总
    接口和抽象类的区别
    详解C#break ,continue, return
  • 原文地址:https://www.cnblogs.com/hrnn/p/13440805.html
Copyright © 2011-2022 走看看