Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predecessor is not present) Inorder successor = 2 Sum = 2 For 7: Inorder predecessor = 3 Inorder successor = 0 (as inorder successor is not present) Sum = 3
Approach: Create an array arr. Store 0 at index 0. Now, store the inorder traversal of tree in the array arr. Then, store 0 at last index. 0’s are stored as inorder predecessor of leftmost leaf and inorder successor of rightmost leaf is not present. Now, perform inorder traversal and while traversing node replace node’s value with arr[i-1] + arr[i+1] and then increment i. In the beginning initialize i = 1. For an element arr[i], the values arr[i-1] and arr[i+1] are its inorder predecessor and inorder successor respectively.
Preorder Traversal before tree modification: 1 2 4 5 3 6 7 Preorder Traversal after tree modification: 11 9 2 3 13 4 3
Time Complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Inorder Successor of a node in Binary Tree
- Inorder predecessor and successor for a given key in BST
- Preorder predecessor of a Node in Binary Tree
- Level Order Predecessor of a node in Binary Tree
- Postorder predecessor of a Node in Binary Search Tree
- Preorder Successor of a Node in Binary Tree
- Postorder successor of a Node in Binary Tree
- Level Order Successor of a node in Binary Tree
- Replace node with depth in a binary tree
- Populate Inorder Successor for all nodes
- Construct a Binary Tree from Postorder and Inorder
- Construct Special Binary Tree from given Inorder traversal
- Sum of the mirror image nodes of a complete binary tree in an inorder way
- Check if an array represents Inorder of Binary Search tree or not
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack