You're sending a constant stream of electrons into the root node of a tree. Each value in the tree tells you how much energy an electron requires at that location.
Electrons always walk to nodes with the lowest possible energy, and electrons can only see their left and right child nodes. When an electron has nowhere to go, it stays in its current location, forcing other electrons that move down the tree into larger-energy paths. Eventually, the whole tree fills with electrons.
Given the root
of the tree, return the order in which electrons fill the tree.
Example 1:
Example 2:
The main idea in this problem is that electrons will always visit lowest-valued nodes first. Heaps are optimal for finding the smallest value over a collection of items, so you can use a Heap to optimize this problem.
At first, electrons can only visit the root node, so you should start the heap out as containing just the root.
You should always pop the heap to get the node with the smallest energy level that's available. You should then add the children to the heap, because electrons are now allowed to visit them. When you do this, you end up visitng all of the nodes in the correct order. Here's the pseudocode for this:
To code this up, the heap needs to store the value of each node node.val
, so that it can order the nodes by their value. The heap also has to keep track of the node itself node
so that it has fast access to the node's children. You can't store nodes in a heap, but you can store extra numbers. The trick is to assign each node a unique id, and use a HashMap to look nodes up based on their id.
Here's the code:
Time Complexity O(nlogn). We end up popping all of the nodes in the tree. Each time you pop a node from a heap, it takes O(log n) time. This gives a total time of O(n log n).
Space Complexity O(n). We have to store the solution in an array, which is O(n) size. We also have to store nodes in the heap, which might grow to O(n) size. This is a total of O(n) + O(n) = O(2n) = O(n) space.