Convert a given tree to its Sum Tree | C # program to convert a tree into its sum tree ; A binary tree node ; Convert a given tree to a tree where every node contains sum of values of nodes in left and right subtrees in the original tree ; Base case ; Store the old value ; Recursively call for left and right subtrees and store the sum as new value of this node ; Return the sum of values of nodes in left and right subtrees old_value of this node ; A utility function to print inorder traversal of a Binary Tree ; Driver Code ; Constructing tree given in the above figure ; Print inorder traversal of the converted tree to test result of toSumTree ( )
using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class GFG { public Node root ; public virtual int toSumTree ( Node node ) { if ( node == null ) { return 0 ; } int old_val = node . data ; node . data = toSumTree ( node . left ) + toSumTree ( node . right ) ; return node . data + old_val ; } public virtual void printInorder ( Node node ) { if ( node == null ) { return ; } printInorder ( node . left ) ; Console . Write ( node . data + " ▁ " ) ; printInorder ( node . right ) ; } public static void Main ( string [ ] args ) { GFG tree = new GFG ( ) ; tree . root = new Node ( 10 ) ; tree . root . left = new Node ( - 2 ) ; tree . root . right = new Node ( 6 ) ; tree . root . left . left = new Node ( 8 ) ; tree . root . left . right = new Node ( - 4 ) ; tree . root . right . left = new Node ( 7 ) ; tree . root . right . right = new Node ( 5 ) ; tree . toSumTree ( tree . root ) ; Console . WriteLine ( " Inorder ▁ Traversal ▁ of ▁ " + " the ▁ resultant ▁ tree ▁ is : " ) ; tree . printInorder ( tree . root ) ; } }