The problem is to find the maximum amount of money you can rob from a binary tree house structure, where adjacent houses cannot be robbed simultaneously. The approach involves traversing the binary tree recursively while maintaining two options for each node:
- Option 0: Maximum amount of money that can be robbed if the current node is robbed.
- Option 1: Maximum amount of money that can be robbed if the current node is not robbed.
Approach
- Define a recursive function travel(TreeNode root) that returns an array of size 2 representing the two options mentioned above.
- In the base case, if the current node is null, return [0, 0].
- Recursively call the travel function for the left and right subtrees to get the options for the left and right child nodes.
- Calculate the options for the current node:
- Option 0: The sum of the current node's value, the maximum amount robbed from the left subtree without robbing its root (leftNodeChoices[1]), and the maximum amount robbed from the right subtree without robbing its root (rightNodeChoices[1]).
- Option 1: The maximum of the sum of the maximum amount robbed from the left subtree (either robbing or not robbing its root) and the maximum amount robbed from the right subtree (either robbing or not robbing its root).
- Return the options array.
Complexity
The time complexity of the solution is O(n), where N is the number of nodes in the binary tree. This is because each node is visited once during the recursive traversal.
The space complexity is also O(n) due to the recursion stack, where N is the height of the binary tree. Additionally, the space complexity includes the arrays created for each node to store the options, but since there are 2 options per node, it remains O(n).
Comments
Post a Comment