编程语言
首页 > 编程语言> > LeetCode-Python-1038. 从二叉搜索树到更大和树

LeetCode-Python-1038. 从二叉搜索树到更大和树

作者:互联网

给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

 

示例:

输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

 

提示:

  1. 树中的节点数介于 1 和 100 之间。
  2. 每个节点的值介于 0 和 100 之间。
  3. 给定的树为二叉搜索树。

思路:

LeetCode-Python-538. 把二叉搜索树转换为累加树一模一样…… 都是右中左的中序遍历,用一个变量记录累加和即可。

class Solution(object):
    def bstToGst(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        self.sum = 0
        
        def inorder(node):
            if not node:
                return
            
            inorder(node.right)
            self.sum += node.val
            node.val = self.sum
            inorder(node.left)
            
        inorder(root)
        return root

标签:node,树到,Python,self,二叉,1038,null,inorder,节点
来源: https://blog.csdn.net/qq_32424059/article/details/90055703