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]
- Print path from root to a given node in a binary tree
- Maximum XOR with given value in the path from root to given node in the tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Find distance from root to given node in a binary tree
- Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree
- Sum of nodes on the longest path from root to leaf node
- GCD from root to leaf path in an N-ary tree
- Find the path from root to the given nodes of a tree for multiple queries
- Find root of the tree where children id sum for every node is given
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print all the paths from root, with a specified sum in Binary tree
- Given a binary tree, print all root-to-leaf paths
- Root to leaf paths having equal lengths in a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.