Likou 538. Convert binary search tree to accumulation tree

Topic source: 538. Convert a binary search tree to an accumulating tree
Topic: Given the root node of a binary search tree, the node values ​​of the tree are different, please convert it into an accumulating tree (Greater Sum Tree), so that The new value of each node node is equal to the sum of the values ​​greater than or equal to node.val in the original tree.

As a reminder, a binary search tree satisfies the following constraints:

A node's left subtree contains only nodes with keys less than the node's key.
A node's right subtree contains only nodes with keys greater than the node's key.
The left and right subtrees must also be binary search trees.
Note: This question and 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ have the same
insert image description here
insert image description here
idea: the form of reverse inorder traversal of the accumulation tree requires each node's The new value is greater than or equal to the sum of the node values. In view of the fact that the binary search tree is an ordered in-order traversal, the array is arranged from small to large, therefore, the idea of ​​reverse in-order traversal is adopted to obtain an array from large to small. Each time a new node is reached, the new value of the node is equal to the new node value plus the accumulated sum of the previous nodes, so that the new value of each node can be greater than or equal to the sum of the nodes.
python code:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        self.total = 0
        def dps(root):
            if not root:
                return 
            dps(root.right)
            self.total += root.val
            root.val = self.total
            dps(root.left)
        dps(root)
        return root

insert image description here
Reference link: [Leetcode] Daily Question of Python Version (20200921): 538. Convert Binary Search Tree to Accumulation Tree

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324340931&siteId=291194637