Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.
For example, the following tree
10 / \ -2 6 / \ / \ 8 -4 7 5
should be changed to
20(4-2+12+6) / \ 4(8-4) 12(7+5) / \ / \ 0 0 0 0
Do a traversal of the given tree. In the traversal, store the old value of the current node, recursively call for left and right subtrees and change the value of current node as sum of the values returned by the recursive calls. Finally return the sum of new value and value (which is sum of values in the subtree rooted with this node).
Inorder Traversal of the resultant tree is: 0 4 0 20 0 12 0
Time Complexity: The solution involves a simple traversal of the given tree. So the time complexity is O(n) where n is the number of nodes in the given Binary Tree.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Convert a given Binary tree to a tree that holds Logical AND property
- Convert a Binary Tree into its Mirror Tree
- Minimum swap required to convert binary tree to binary search tree
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a tree to forest of even nodes
- Convert Ternary Expression to a Binary Tree
- Convert left-right representation of a binary tree to down-right
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a Binary Tree to a Circular Doubly Link List
Improved By : shrikanth13