zoukankan      html  css  js  c++  java
  • [LeetCode] 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),得到二叉树最大深度

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (root == nullptr)
                return 0;
            int left = maxDepth(root->left);
            int right = maxDepth(root->right);
            return max(left, right) + 1;
        }
    };
    // 6 ms

    利用层次遍历在遍历每一层时引入一个计数变量,统计一共计算的层数,即可得到二叉树的最大深度。

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (root == nullptr)
                return 0;
            int depth = 0;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                int n = q.size();
                for (int i = 0; i != n; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    if (node->left != nullptr)
                        q.push(node->left);
                    if (node->right != nullptr)
                        q.push(node->right);
                }
                depth++;
            }
            return depth;
        }
    };
    // 6 ms
  • 相关阅读:
    js正则表达式大全(2)
    Magic Trackpad 2 on win10 x64
    Google 日历短信通知没有了
    Ueditor 1.4.3 jsp utf-8版Bug修复
    [转]eclipse中build workspace的相关优化
    Hello,
    EpCloud开发日志
    为服务创建安装程序
    winform 通过WCF上传Dataset数据
    opcrcw.da.dll 和.net 4.0
  • 原文地址:https://www.cnblogs.com/immjc/p/7149204.html
Copyright © 2011-2022 走看看