Convert a Binary Tree into a Sum Tree
⬅ Previous TopicConvert a Binary Tree into a Doubly Linked List
Next Topic ⮕Find Minimum Swaps Required to Convert a Binary Tree into a BST
Next Topic ⮕Find Minimum Swaps Required to Convert a Binary Tree into a BST
Solution
Algorithm Steps
Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def toSumTree(root):
if root is None:
return 0
old_val = root.val
left_sum = toSumTree(root.left)
right_sum = toSumTree(root.right)
root.val = left_sum + right_sum
return root.val + old_val
# Example usage:
if __name__ == '__main__':
# Construct the binary tree:
# 10
# / \
# -2 6
# / \
# 8 -4
root = TreeNode(10, TreeNode(-2, TreeNode(8), TreeNode(-4)), TreeNode(6))
toSumTree(root)
# The tree is now converted into a sum tree