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
  • 相关阅读:
    批处理学习笔记9
    批处理学习笔记8
    批处理学习笔记10
    批处理学习笔记7
    批处理学习笔记6
    批处理学习笔记系列
    批处理学习笔记5
    批处理学习笔记3
    批处理学习笔记4
    批处理学习笔记2
  • 原文地址:https://www.cnblogs.com/immjc/p/7149204.html
Copyright © 2011-2022 走看看