You're a software developer, and you need to install packages in the correct order.
Given the root
node of the dependency tree, where each parent package must be installed before its children packages, return a valid order in which you can install the packages.
Example:
Here's a correct solution:
Here's an incorrect solution:
This solution fails because the "set" package must be installed after the "python" and "hash" packages.
1. Recursion
In order to solve this problem, we must install the parent packages before the children packages. The recursion is to first install the package on the current node, and then afterwards install it on all the children nodes. Here's the recursion:
Another way to come up with this recursion is to think about tree traversals, since we want to walk through all the nodes in the tree. There are 3 options - preorder c L R
, inorder L c R
and postorder L R c
.
Preorder traversals visit the current node, then all the left children, and then all the right children, c L R
. This holds for every node that a preorder traversal visits. So we can use a preorder traversal here to always install the parents first, then the children. And you can confirm that the above recursion is really just a preorder traversal.
2. Base case
As usual, the traversal should stop when we get to a node that's null. Here's the base case:
3. Code
To code this up, just combine the recursion and base case.
Time Complexity O(n) to loop through every node.
Space Complexity O(n) for the Call Stack.
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()
TreeNode.of
function can be used to create an entire binary tree using 1 line of code. The input is a BFS traversal of the tree including nulls, and the output is the root node of the tree.TreeNode.of([1, None, 2, None, 3])
ListNode.of
function lets you create an entire Linked List using 1 line of code. The input is an array, and the output is the head of the Linked List.ListNode.of([1, 2, 3])
ListNode.of([1, 2, 3], 1)
GraphNode.of
function lets you create an entire Graph using 1 line of code. The input is an Adjacency Matrix, and the output is the first node in the matrix.GraphNode.of([ ['A', 1, 2], ['B', 2], ['C', 0] ])
[['__init__', 15], ['add', 16], ['get']]
c = MyClass(15) c.add(16) c.get()