![]() |
VOOZH | about |
There are Houses arranged in the form of a Binary tree. There is only one entrance to the houses which is the root of a tree. It will automatically contact the police if two directly linked houses are broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Examples:
Input: root = [3, 4, 5, 1, 3, null, 1]
3
/ \
4 5
/ \ \
1 3 1
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.Input: root = [3, 2, 3, null, 3, null, 1]
3
/ \
2 3
\ \
3 1
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Approach: To solve the problem follow the below steps:
Below is the implementation of above approach:
9
Time Complexity: O(N) Since we are traversing the whole tree and there are total N nodes in the tree
Auxiliary Space: O(N) to store the answers in dp and the recursion stack space