1. Exponential Recursion (Root vs Grandchildren)
Intuition
If we rob root, sum root.val + rob(root.left.grandchildren) + rob(root.right.grandchildren). If we don't, sum rob(root.left) + rob(root.right). Take max.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return 0.
- Step 2: valRob = root.val + recurse on grandchildren.
- Step 3: valSkip = recurse on root.left + recurse on root.right.
- Step 4: Return max(valRob, valSkip).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int rob(TreeNode* root) { if (!root) return 0; int robRoot = root->val; if (root->left) { robRoot += rob(root->left->left) + rob(root->left->right); } if (root->right) { robRoot += rob(root->right->left) + rob(root->right->right); } int skipRoot = rob(root->left) + rob(root->right); return max(robRoot, skipRoot); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(2^n)— Overlapping subproblems cause exponential branching. - Space complexity:
O(h)— Call stack bounded by tree height h.