【LeetCode】104. 二叉树的最大深度

题目

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

返回它的最大深度 3 。

本题同【剑指Offer】面试题55 - I. 二叉树的深度

思路一:递归

代码

时间复杂度:O(n),每个节点访问一次
空间复杂度:O(n),树的高度

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) {
            return 0;
        }
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return 1 + max(left, right);
    }
};

思路二:迭代(层次遍历)

代码

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;     
        queue<TreeNode*> que;
        que.push(root);
        int toDeleted = 1, next = 0, res = 0;
        while (!que.empty()) {
            TreeNode *p = que.front();
            que.pop();
            if (p->left) {
                que.push(p->left);
                ++next;
            } 
            if (p->right) {
                que.push(p->right);
                ++next;
            } 
            --toDeleted;
            if (toDeleted == 0) {
                toDeleted = next;
                next = 0;                
                ++res;
            }
        }
        return res;
    }
};

另一种写法

使用队列大小。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;     
        queue<TreeNode*> que;
        que.push(root);
        int res = 0;
        while (!que.empty()) {
            for (auto i = que.size(); i > 0; --i) {
                TreeNode *p = que.front();
                que.pop();
                if (p->left) que.push(p->left);
                if (p->right) que.push(p->right);
            }
            ++res;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/galaxy-hao/p/12386731.html