Files
leetcode-master/problems/0104.二叉树的最大深度.md
youngyangyang04 25772fab9d Update
2020-08-08 20:09:22 +08:00

1.2 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路

C++代码

递归

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

迭代法

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        int depth = 0;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()) {
            int size = que.size(); // 必须要这么写要固定size大小
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if (node->left) que.push(node->left);
                if (node->right) que.push(node->right);
            }
        }
        return depth;
    }
};

更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。