Given a binary tree, change the value in each node to sum of all the values in the nodes in the right subtree including its own.
Input : 1 / \ 2 3 Output : 4 / \ 2 3 Input : 1 / \ 2 3 / \ \ 4 5 6 Output : 10 / \ 7 9 / \ \ 4 5 6
Approach : The idea is to traverse the given binary tree in bottom up manner. Recursively compute the sum of nodes in right and left subtrees. Accumulate sum of nodes in the right subtree to the current node and return sum of nodes under current subtree.
Below is the implementation of above approach.
Inorder traversal of the modified tree is 4 7 5 10 9 6
Time Complexity: O(n)
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.
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf
- Node having maximum number of nodes less than its value in its subtree
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Convert left-right representation of a binary tree to down-right
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Subtree of all nodes in a tree using DFS
- Check whether every node of binary tree has a value K on itself or its any immediate neighbours
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Check if two nodes are in same subtree of the root node
- Queries for the number of nodes having values less than V in the subtree of a Node
- Queries to find the Minimum Weight from a Subtree of atmost D-distant Nodes from Node X
- Subtree with given sum in a Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.