Q:
给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node
的新值等于原树中大于或等于 node.val
的值之和。
提醒一下,二叉搜索树满足下列约束条件:
- 节点的左子树仅包含键小于节点键的节点。
- 节点的右子树仅包含键大于节点键的节点。
- 左右子树也必须是二叉搜索树。
思路:同 538. 把二叉搜索树转换为累加树 设置一个全局的变量 遍历右子树,做累加
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.lSum = 0
def bstToGst(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
self.bstToGst(root.right)
self.lSum += root.val
root.val = self.lSum
self.bstToGst(root.left)
return root