GeeksforGeeks » Trees specific questions
Given a node of BST, make it the root
(5 posts)-
Given a node of a BST, modify it in such a way that the given node becomes the root. The tree should still be BST. One way I could get is store the Inoder traversal of the tree. Find that node in the traversal and recursively make the BST.
-
Let given a node of BST (B) is n. These are the steps to be followed
1. Start constructing new BST tree(B_new) with n as root.
2. Do level order traversal in given BST (B) and add each node to the new BST(B_new) tree.
3. As BST do not allow the duplicate nodes, skip the node n in given BST(B) i.e. don't add this node to new BST while constructing.
At the end we will get new BST as given node n is the root.
For example:
35
20 40
10 25 30 50
is the given BST. Now make 30 as the root.
Sol: Step1 take 30 as root and construct new BST.
30
Step2: Now do level order traversal and add each visited node to new BST. Level order traversal of given BST is 35 20 40 10 25 30 5030 -> 30 -> 30 --> 30
35 20 35 20 35 20 35
40 10 40
do the same procedure, finally we get
30
20 35
10 25 40
50Thanks.
-
void RearrangePointersLeft(nodemary*& root, nodemary*& target){ nodemary* tmp; tmp = root; tmp->left = NULL; root = target; root->right = tmp; } void RearrangePointersRight(nodemary*& root, nodemary*& target){ nodemary* tmp; tmp = root; tmp->right = NULL; root = target; root->left = tmp; } void ModifyBST(nodemary*& root, nodemary*& target){ if (root == NULL){ return; } if (root->value < target->value){ ModifyBST(root->right, target); RearrangePointersRight(root, target); } else if (root->value > target->value){ ModifyBST(root->left, target); RearrangePointersLeft(root, target); } } -
The above procedure is similar to balancing a BST( right rotate/left rotate ) wrt the node and the root.
root
/ \
n1 n2
/ \ / \
newroot n3 n4 n5
/ \
n6 n7after the procedure
newroot
/ \
n6 root
/ \
n1 n2
/ \ / \
n7 n3 n4 n5 -
The above procedure is similar to balancing a BST( right rotate/left rotate ) wrt the node and the root.
.................................................. root
.............................................. / \
.......................................... n1 n2
.................................... / \ / \
............................. newroot n3 n4 n5
........................... / \
........................... n6 n7after the procedure
................................................ newroot
................................................ / \
............................................ n6 root
....................................................... / \
....................................................... n1 n2
................................................... / \ / \
................................................ n7 n3 n4 n5
Reply
You must log in to post.