Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
/ \ / \
6 5 7 8
/ \ / \
8 10 12 7
- For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor = 3. Sum = 3.
- For Node 3: Preorder predecessor = 2, preorder successor = 6. Sum = 8.
- For Node 6: Preorder predecessor = 3, preorder successor = 5. Sum = 8.
- For Node 5: Preorder predecessor = 6, preorder successor = 4. Sum = 10.
- For Node 4: Preorder predecessor = 5, preorder successor = 7. Sum = 12.
- For Node 7: Preorder predecessor = 4, preorder successor = 8. Sum = 12.
- For Node 8: Preorder predecessor = 7, preorder successor = 0 (as preorder successor is not present). Sum = 7.
Approach: The given problem can be solved by storing the preorder traversal of the tree in an auxiliary array and then replace each node with the sum of the preorder predecessor and preorder successor. Follow the below steps to solve the problem:
- Declare a function, say replaceNode(root, A, idx) to perform the preorder traversal on the tree with the starting index as i and perform the following steps:
- If the root node is NULL, then return from the function.
- Replace the value of the current node as V[i – 1] + V[i + 1] as for element V[i], the values V[i – 1] and V[i + 1] are its preorder predecessor and preorder successor respectively.
- Recursively call for the function replaceNode(root->left, A, idx + 1) and replaceNode(root->right, A, idx + 1).
- Initialize a vector V that stores the preorder traversal of the given tree.
- Store 0 at index 0 as preorder predecessor of the leftmost leaf node doesn’t exist.
- Perform the preorder traversal on the given tree and store the preorder traversal in vector V.
- Store 0 at the end of the vector as preorder successor of the rightmost leaf node is not present.
- Call the function replaceNode(root, A, 1) to replace each node with the required sum.
- After completing the above steps, print the preorder of the modified tree.
Below is the implementation of the above approach:
Preorder Traversal before modification of tree: 2 3 6 5 4 7 8 Preorder Traversal after modification of tree: 3 8 8 10 12 12 7
Time Complexity: O(N)
Auxiliary Space: O(N)