Mariusz Najwer’s Post

Spring cleaning 🌳 ✂️ The task is to remove every subtree containing only 0s from a binary tree. The simplest way to achieve that is setting null on nodes without children and with value 0, so the node gets cut off from our tree. I traverse the tree bottom-up (dfs, post-order) because children must be pruned first. This lets me safely check if the current node forms a zero-only subtree. ✨ Pruned nodes don't vanish. They turn unreachable. Pruned nodes get detached by returning null from the recursive call to their parent. The parent's reference (root.left or root.right) becomes null, making the entire zero-subtree unreachable from the main tree structure. In JavaScript, the garbage collector automatically detects these orphaned objects during its next cycle and reclaims their memory, no manual cleanup or deletion required. #javascript #node #interview

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories