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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Print K inorder successors of a Binary Tree in O(1) space
- Construct Special Binary Tree from given Inorder traversal
- Check if Inorder traversal of a Binary Tree is palindrome or not
- Check if an array represents Inorder of Binary Search tree or not
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Sum of the mirror image nodes of a complete binary tree in an inorder way
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Search a node in Binary Tree
- K-th ancestor of a node in Binary Tree