VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximizing-robbery-in-binary-tree-houses-without-alerting-police/

⇱ Maximizing Robbery in Binary Tree Houses without Alerting Police - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximizing Robbery in Binary Tree Houses without Alerting Police

Last Updated : 18 Dec, 2023

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:

  • We will start from the root of tree and recursively check whether we can take the current node or not,
  • If we take the current node then we will not be able to take the childs of the node we have to check if the grandchildrens exists or not
  • Then we decide whether to pick them or not, We will do this recursively from the root to leaves of the tree and store the maximum amount that the robber can rob till that node and
  • Modify the value of that node since we can encounter the same node in future we will mark it via using a dp set which ensures that we does not visit that node again and
  • Like this we start updating the node value with the maximum amount that robber can rob at that node level and
  • We update the tree in bottom-up fashion from leaves to the root and when we update the root value it contains the desired result that the maximum amount robber can rob if it starts from the root.

Below is the implementation of above approach:



Output
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

Comment