[LeetCode] Maximum Depth of Binary Tree

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[LeetCode] Maximum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):104 Maximum Depth of Binary Tree

LeetCode 104. Maximum Depth of Binary Tree

leetcode:Maximum Depth of Binary Tree

LeetCode104. Maximum Depth of Binary Tree

[leetcode] Maximum Depth of Binary Tree

leetcode104-Maximum Depth of Binary Tree