Reputation: 221
I got this question from my friend's interview: Given a binary tree, print the array of nodes(at most two nodes) from all levels that near the middle of the tree. Here is an example:
1The output is
/ \
2 3
/ \ \
4 5 9
/
10
[ [2,3], [5,9], [10] ]
.NULL
, put a flag(maybe -1 or sth else) into the slot. At the end, print out all nodes in the middle of each array.[1], [2,3], [4,5,-1,9],[-1,-1,10,-1]
, after this process, print out all middle values in the array which is not -1.Upvotes: 0
Views: 579
Reputation: 121
We can never be sure if an element exists in an ith level until we've traversed all the elements of the tree. Hence, the time complexity can never be optimised better than O(n), which is the same as the algorithm proposed by you.
The only problem in your solution is that for each level a seperate array is required to be maintained. Though asymptotically the space complexity remains the same, in absolute numbers it becomes extra usage.
What you can do is the following:
This algorithm works better space complexity wise for sparse trees.
Hope this helps!
Upvotes: 0
Reputation: 26
Go in-order traversal the tree and also keep the node's level
Node: 4-2-5-1-3-10-9
Level: 2-1-2-0-1-3-2
Now for the level output, we start from level 0, find left side first occurrence of 1 -- the corresponding number is 2, find the right side first occurrence of 1 -- the corresponding number is 3, so the level 1 output is <2,3>
do the same thing for level 2 output is <5,9>
for level 3 output is just<10>
Time complexity O(n) Space complexity O(n)
Same as level order traversal solution
Upvotes: 1
Reputation: 11284
The only way I can think of for this question is, from the root, we can divide the nodes into two type : left side of the root and right side of the root. And for each level, for the left side nodes, we find the right most node, and for the right side, we find the left most node. Hope this will help you!
Upvotes: 1