75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

104. Maximum Depth of Binary Tree

O(N) Time and O(H) Space,(DFS) More preferred than iterative

Code

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

O(N) Time and O(N) Space (BFS), using level order traversal

Code

class Solution{
public:
    int maxDepth(TreeNode *root){
        if (root == NULL) return 0;

        queue<TreeNode *> q;
        q.push(root);
        int depth = 0;

        while (!q.empty())        {
            int sz = q.size();
            for (int i = 0; i < sz; i++)            {
                TreeNode *node = q.front();
                q.pop();
                if (node->left != NULL)
                    q.push(node->left);
                if (node->right != NULL)
                    q.push(node->right);
            }
            depth++;
        }
        return depth;
    }
};