[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

 

posted @ 2017-07-11 10:12  immjc  阅读(91)  评论(0编辑  收藏  举报