shlogg · Early preview
Prashant Mishra @prashantrmishra

Optimizing Binary Tree Node Robbery In O(n) Time Complexity

Robbing a binary tree: O(n) time complexity and space complexity using DP map and recursive stack space. Maximize node values by considering or not considering the current node's value.

Problem
TC: O(n) where n is the no. of nodes in the tree
SC: O(n) for using dp map and O(n) for recursive stack space

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    /*
cases for the any give node
    //consider
    if root.val is considered then we can explore root....