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]
- Delete all the nodes from a doubly linked list that are smaller than a given value
- Count all pairs of adjacent nodes whose XOR is an odd number
- Quick Sort vs Merge Sort
- Print nodes in top view of Binary Tree | Set 2
- Samsung Semiconductor Institute of Research(SSIR Software) intern/FTE | Set-3
- Count all possible position that can be reached by Modified Knight
- Find the number of distinct islands in a 2D matrix
- Numbers less than N which are product of exactly two distinct prime numbers
- Length of largest sub-array having primes strictly greater than non-primes
- Minimum odd cost path in a matrix
- Generating OTP (One time Password) in PHP
- Product of 2 numbers using recursion | Set 2
- Program for SSTF disk scheduling algorithm
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.