is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.
CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.
Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.
Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.
This question is completely different than tree walk algorithm.
- mvatankh@stevens.edu February 07, 2018There are two different solutions to this problem. Running time of them is O(n lg n) and O(n).
Solution 1 ( O(n lg n) ):
Set a key value to each node. Set the key of root to n. Start BFS from the root. At each step when you visit a node, set the left child key to nodes’ key minus one and the right child key to nodes’ key plus one; then insert the node at the end of an array. After BFS is finished, sort the array based on the key using a stable sorting algorithm in O(n lg n).
Solution 2 ( O(n) ):
Create an array of size 2n. Simulate the counting sort during BFS, such that after your BFS each index includes the count of nodes with that key. Repeat BFS one more time; insert the elements in the sorted format in the second array of size n by using the information of the first array in a counting sort manner. This takes O(n) to finish.
Note: Both algorithms need O(n) space.