Replace each node in binary tree with the sum of its inorder predecessor and successor
Last Updated : 4 Nov, 2024
Given a binary tree containing n nodes. The task is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor.
[Expected Approach - 1] Using In-Order Traversal and Array - O(n) Time and O(n) Space
Create an array arr. Store 0 at index 0. Now, store the in-order 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.
Below is the implementation of the above approach:
C++
// C++ program to replace each node // in binary tree with the sum of // its inorder predecessor and successor#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Recursive Function which will replace node value voidreplaceNodeRecur(Node*root,int&index,vector<int>&arr){if(root==nullptr)return;replaceNodeRecur(root->left,index,arr);// replace the node value.root->data=arr[index-1]+arr[index+1];index++;replaceNodeRecur(root->right,index,arr);}// Function to store in-order traversal in array.voidstoreInorder(Node*root,vector<int>&arr){if(root==nullptr)return;storeInorder(root->left,arr);arr.push_back(root->data);storeInorder(root->right,arr);}// Function to replace the nodes with // sum of inorder predecessor and successor.voidreplaceNodeWithSum(Node*root){if(root==nullptr)return;// Array to store inorder traversal.vector<int>arr;arr.push_back(0);// Store in-order storeInorder(root,arr);arr.push_back(0);intindex=1;replaceNodeRecur(root,index,arr);}voidinOrder(Node*root){if(root==nullptr)return;inOrder(root->left);cout<<root->data<<" ";inOrder(root->right);}intmain(){// Binary tree// 1// / \ // 2 3// / \ / \ // 3 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);replaceNodeWithSum(root);inOrder(root);return0;}
Java
// Java program to replace each node // in binary tree with the sum of // its inorder predecessor and successorimportjava.util.ArrayList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Recursive Function which will replace node value staticvoidreplaceNodeRecur(Noderoot,int[]index,ArrayList<Integer>arr){if(root==null)return;replaceNodeRecur(root.left,index,arr);// replace the node value.root.data=arr.get(index[0]-1)+arr.get(index[0]+1);index[0]++;replaceNodeRecur(root.right,index,arr);}// Function to store in-order traversal in array.staticvoidstoreInorder(Noderoot,ArrayList<Integer>arr){if(root==null)return;storeInorder(root.left,arr);arr.add(root.data);storeInorder(root.right,arr);}// Function to replace the nodes with // sum of inorder predecessor and successor.staticvoidreplaceNodeWithSum(Noderoot){if(root==null)return;// Array to store inorder traversal.ArrayList<Integer>arr=newArrayList<>();arr.add(0);// Store in-order storeInorder(root,arr);arr.add(0);int[]index={1};replaceNodeRecur(root,index,arr);}staticvoidinOrder(Noderoot){if(root==null)return;inOrder(root.left);System.out.print(root.data+" ");inOrder(root.right);}publicstaticvoidmain(String[]args){// Binary tree// 1// / \// 2 3// / \ / \// 3 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);}}
Python
# Python program to replace each node # in binary tree with the sum of # its inorder predecessor and successorclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive Function which will replace# node value defreplaceNodeRecur(root,index,arr):ifrootisNone:returnreplaceNodeRecur(root.left,index,arr)# replace the node value.root.data=arr[index[0]-1]+arr[index[0]+1]index[0]+=1replaceNodeRecur(root.right,index,arr)# Function to store in-order traversal # in array.defstoreInorder(root,arr):ifrootisNone:returnstoreInorder(root.left,arr)arr.append(root.data)storeInorder(root.right,arr)# Function to replace the nodes with # sum of inorder predecessor and successor.defreplaceNodeWithSum(root):ifrootisNone:return# Array to store inorder traversal.arr=[0]# Store in-order storeInorder(root,arr)arr.append(0)index=[1]replaceNodeRecur(root,index,arr)definOrder(root):ifrootisNone:returninOrder(root.left)print(root.data,end=" ")inOrder(root.right)if__name__=="__main__":# Binary tree# 1# / \# 2 3# / \ / \# 3 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)replaceNodeWithSum(root)inOrder(root)
C#
// C# program to replace each node // in binary tree with the sum of // its inorder predecessor and successorusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Recursive Function which will replace // node value staticvoidreplaceNodeRecur(Noderoot,refintindex,List<int>arr){if(root==null)return;replaceNodeRecur(root.left,refindex,arr);// replace the node value.root.data=arr[index-1]+arr[index+1];index++;replaceNodeRecur(root.right,refindex,arr);}// Function to store in-order traversal in array.staticvoidstoreInorder(Noderoot,List<int>arr){if(root==null)return;storeInorder(root.left,arr);arr.Add(root.data);storeInorder(root.right,arr);}// Function to replace the nodes with // sum of inorder predecessor and successor.staticvoidreplaceNodeWithSum(Noderoot){if(root==null)return;// Array to store inorder traversal.List<int>arr=newList<int>{0};// Store in-order storeInorder(root,arr);arr.Add(0);intindex=1;replaceNodeRecur(root,refindex,arr);}staticvoidinOrder(Noderoot){if(root==null)return;inOrder(root.left);Console.Write(root.data+" ");inOrder(root.right);}staticvoidMain(){// Binary tree// 1// / \// 2 3// / \ / \// 3 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);}}
JavaScript
// JavaScript program to replace each node // in binary tree with the sum of // its inorder predecessor and successorclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive Function which will replace node value functionreplaceNodeRecur(root,index,arr){if(root===null)return;replaceNodeRecur(root.left,index,arr);// replace the node value.root.data=arr[index[0]-1]+arr[index[0]+1];index[0]++;replaceNodeRecur(root.right,index,arr);}// Function to store in-order traversal in array.functionstoreInorder(root,arr){if(root===null)return;storeInorder(root.left,arr);arr.push(root.data);storeInorder(root.right,arr);}// Function to replace the nodes with // sum of inorder predecessor and successor.functionreplaceNodeWithSum(root){if(root===null)return;// Array to store inorder traversal.letarr=[0];// Store in-order storeInorder(root,arr);arr.push(0);letindex=[1];replaceNodeRecur(root,index,arr);}functioninOrder(root){if(root===null)return;inOrder(root.left);console.log(root.data);inOrder(root.right);}// Binary tree// 1// / \// 2 3// / \ / \// 3 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);
Output
2 9 3 11 4 13 3
[Expected Approach - 2] Without Using Array - O(n) Time and O(h) Space
The idea is to perform recursive in-order traversal while maintaining the previous node pointer and previous node's predecessor value. For each node curr, set the value of previous node to sum of (predecessor value + current node value). Update previous node and predecessor value accordingly.
Below is the implementation of the above approach:
C++
// C++ program to replace each node // in binary tree with the sum of // its inorder predecessor and successor#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Recursive Function which will replace node value voidreplaceNodeRecur(Node*root,int&pred,Node*&prev){if(root==nullptr)return;// Recursively process left subtree.replaceNodeRecur(root->left,pred,prev);// If previous node exists, then// update its value.if(prev!=nullptr){inttmp=prev->data;prev->data=pred+root->data;pred=tmp;}// Update prev pointerprev=root;// Recursively process right subtree.replaceNodeRecur(root->right,pred,prev);}// Function to replace the nodes with // sum of inorder predecessor and successor.voidreplaceNodeWithSum(Node*root){if(root==nullptr)return;intpred=0;Node*prev=nullptr;replaceNodeRecur(root,pred,prev);// Update the value of last node as // it is not covered in in-order traversal.prev->data=pred;}voidinOrder(Node*root){if(root==nullptr)return;inOrder(root->left);cout<<root->data<<" ";inOrder(root->right);}intmain(){// Binary tree// 1// / \ // 2 3// / \ / \ // 3 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);replaceNodeWithSum(root);inOrder(root);return0;}
Java
// Java program to replace each node // in binary tree with the sum of // its inorder predecessor and successorclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classMain{// Recursive Function which will replace node value staticvoidreplaceNodeRecur(Noderoot,int[]pred,Node[]prev){if(root==null)return;// Recursively process left subtree.replaceNodeRecur(root.left,pred,prev);// If previous node exists, then// update its value.if(prev[0]!=null){inttmp=prev[0].data;prev[0].data=pred[0]+root.data;pred[0]=tmp;}// Update prev pointerprev[0]=root;// Recursively process right subtree.replaceNodeRecur(root.right,pred,prev);}// Function to replace the nodes with // sum of inorder predecessor and successor.staticvoidreplaceNodeWithSum(Noderoot){if(root==null)return;int[]pred={0};Node[]prev={null};replaceNodeRecur(root,pred,prev);// Update the value of last node as // it is not covered in in-order traversal.prev[0].data=pred[0];}staticvoidinOrder(Noderoot){if(root==null)return;inOrder(root.left);System.out.print(root.data+" ");inOrder(root.right);}publicstaticvoidmain(String[]args){// Binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);}}
Python
# Python program to replace each node # in binary tree with the sum of # its inorder predecessor and successorclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Recursive Function which will replace node value defreplaceNodeRecur(root,pred,prev):ifrootisNone:return# Recursively process left subtree.replaceNodeRecur(root.left,pred,prev)# If previous node exists, then# update its value.ifprev[0]isnotNone:tmp=prev[0].dataprev[0].data=pred[0]+root.datapred[0]=tmp# Update prev pointerprev[0]=root# Recursively process right subtree.replaceNodeRecur(root.right,pred,prev)# Function to replace the nodes with # sum of inorder predecessor and successor.defreplaceNodeWithSum(root):ifrootisNone:returnpred=[0]prev=[None]replaceNodeRecur(root,pred,prev)# Update the value of last node as # it is not covered in in-order traversal.prev[0].data=pred[0]definOrder(root):ifrootisNone:returninOrder(root.left)print(root.data,end=" ")inOrder(root.right)if__name__=="__main__":# Binary tree# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)replaceNodeWithSum(root)inOrder(root)
C#
// C# program to replace each node // in binary tree with the sum of // its inorder predecessor and successorusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Recursive Function which will replace node value staticvoidreplaceNodeRecur(Noderoot,refintpred,refNodeprev){if(root==null)return;// Recursively process left subtree.replaceNodeRecur(root.left,refpred,refprev);// If previous node exists, then// update its value.if(prev!=null){inttmp=prev.data;prev.data=pred+root.data;pred=tmp;}// Update prev pointerprev=root;// Recursively process right subtree.replaceNodeRecur(root.right,refpred,refprev);}// Function to replace the nodes with // sum of inorder predecessor and successor.staticvoidreplaceNodeWithSum(Noderoot){if(root==null)return;intpred=0;Nodeprev=null;replaceNodeRecur(root,refpred,refprev);// Update the value of last node as // it is not covered in in-order traversal.prev.data=pred;}staticvoidinOrder(Noderoot){if(root==null)return;inOrder(root.left);Console.Write(root.data+" ");inOrder(root.right);}staticvoidMain(string[]args){// Binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);}}
JavaScript
// JavaScript program to replace each node // in binary tree with the sum of // its inorder predecessor and successorclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Recursive Function which will replace node value functionreplaceNodeRecur(root,pred,prev){if(root===null)return;// Recursively process left subtree.replaceNodeRecur(root.left,pred,prev);// If previous node exists, then// update its value.if(prev[0]!==null){lettmp=prev[0].data;prev[0].data=pred[0]+root.data;pred[0]=tmp;}// Update prev pointerprev[0]=root;// Recursively process right subtree.replaceNodeRecur(root.right,pred,prev);}// Function to replace the nodes with // sum of inorder predecessor and successor.functionreplaceNodeWithSum(root){if(root===null)return;letpred=[0];letprev=[null];replaceNodeRecur(root,pred,prev);// Update the value of last node as // it is not covered in in-order traversal.prev[0].data=pred[0];}functioninOrder(root){if(root===null)return;inOrder(root.left);console.log(root.data);inOrder(root.right);}// Binary tree// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);replaceNodeWithSum(root);inOrder(root);