Pergunta de entrevista da empresa Microsoft

Given a binary tree, each node has a null "next node" , which points to the next node in the same level (left to right). Update the given tree so that each node has a value in their "next" field. Level 2/Bonus: do it in O(1) time, using iteration instead of recursion.

Resposta da entrevista

Sigiloso

2 de out. de 2018

Level 2/Bonus: do it in O(1) time, using iteration instead of recursion. Create a list of key-value pairs, such that the key is the level, and the value is the last seen node at the particular height in the tree. Use in order traversal to update the list as new heights are discovered. For each node, if there's a key-value pair, access the node in the value, update it's next field with the current node. then replace the value with the current node. O(N) Time complexity - iterate over each of the nodes in the tree. O(H) Space complexity - where H is the height of the tree. (due to the list of key-value pairs) Level 2: store the binary tree in an array, iterate over each next element in the array. for each root node you iterate over, point the left node to the right node before moving on. (During the interview the issue was raised about how to connect the nodes if the root wasn't the same. Interviewer suggested using an extra variable to keep track while iterating. )