Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 661 Bytes

104. Maximum Depth of Binary Tree.md

File metadata and controls

33 lines (29 loc) · 661 Bytes
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};
// BFS
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> q({root});
        int depth = 0;
        while (!q.empty()) {
            depth++;
            for (int i = q.size(); i > 0; --i) {
                TreeNode* node = q.front(); q.pop();
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        return depth;
    }
};