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.
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.
- Inorder predecessor and successor for a given key in BST
- Inorder Successor of a node in Binary Tree
- Preorder predecessor of a Node in Binary Tree
- Postorder predecessor of a Node in Binary Search Tree
- Level Order Predecessor of a node in Binary Tree
- Populate Inorder Successor for all nodes
- 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
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Sum of the mirror image nodes of a complete binary tree in an inorder way
- Construct a Binary Tree from Postorder and Inorder
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Replace node with depth in a binary tree
- Number of full binary trees such that each node is product of its children
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Cartesian tree from inorder traversal | Segment Tree
- Construct Special Binary Tree from given Inorder traversal
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Check if an array represents Inorder of Binary Search tree or not