首页 > 其他 > 详细

[LeetCode] Maximum Depth of Binary Tree

时间:2017-07-11 10:57:08      阅读:297      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/immjc/p/7149204.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!