[Leetcode] Maximum Depth of Binary Tree

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Maximum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。

Maximum Depth of Binary Tree 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/


Description

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.

Solution


class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int res = 0;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        while (!q.empty()) {
            TreeNode* node = q.front();
            q.pop();
            if (node != NULL) {
                if (node -> left != NULL)
                    q.push(node -> left);
                if (node -> right != NULL)
                    q.push(node -> right);
            } else {
                res++;
                if (!q.empty())
                    q.push(NULL);
            }
        }
        return res;
    }
};



解题描述

这道题题意是求二叉树的深度,上面的解法用到的是迭代法层次遍历来计算二叉树深度,使用的方法和层次遍历相近。

以上是关于[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