Given a Binary tree, the task is to sort the particular path from to a given node of the binary tree. You are given a Key Node and Tree. The task is to sort the path till that particular node.
Input : 3 / \ 4 5 / \ \ 1 2 6 key = 2 Output : 2 / \ 3 5 / \ \ 1 4 6 Inorder :- 1 3 4 2 5 6 Here the path from root to given key is sorted from 3(root) to 2(key). Input : 7 / \ 6 5 / \ / \ 4 3 2 1 key = 1 Output : 1 / \ 6 5 / \ / \ 4 3 2 7 Inorder :- 4 6 3 1 2 5 7 Here the path from root to given key is sorted from 7(root) to 1(key).
Algorithm: Following is simple algorithm to sort the path top to bottom (increasing order).
- Find path from root to given key node and store it in a priority queue.
- Replace the value of node with the priority queue top element.
- if left pq size is greater than replace the value of node with left pq after pop out the element.
- if right pq size is greater then replace the value of node with right pq after pop out the element.
- Print the tree in inorder.
Below is the implementation of the above approach:
1 3 4 2 5 6
Time Complexity: O(N logN) [N for traversing all the node and N*logN for priority queue]
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live