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.
- 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 all root to leaf path sum of a Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Maximize count of set bits in a root to leaf path in a 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
- GCD from root to leaf path in an N-ary tree
- Sum of nodes on the longest path from root to leaf node
- 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
- Print all the paths from root, with a specified sum in Binary tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Given a binary tree, print all root-to-leaf paths
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Find maximum GCD value from root to leaf in a Binary tree