给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同
示例 1:
输入:[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]
示例 2:
输入:root = [0,null,1]
输出:[1,null,1]
示例 3:
输入:root = [1,0,2]
输出:[3,3,2]
示例 4:
输入:root = [3,2,4,1]
输出:[7,9,4,10]
提示:
树中的节点数介于 0 和 104 之间。
每个节点的值介于 -104 和 104 之间。
树中的所有值 互不相同 。
给定的树为二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
参考:
python
# 0538.二叉搜索树转为累加树
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
"""
反中序递归,通过前序节点值pre完成累加操作
:param root:
:return:
"""
pre = 0
def travel(cur):
nonlocal pre
if not cur:
return
travel(cur.right)
cur.val += pre
pre = cur.val
travel(cur.left)
travel(root)
return root
class Solution2:
def convertBST(self, root: TreeNode) -> TreeNode:
"""
反中序迭代,前序节点值pre完成累加操作
:return:
"""
pre = 0
def travel(root):
nonlocal pre
stack = []
cur = root
while cur or stack:
if cur:
stack.append(cur)
cur = cur.right
else:
cur = stack.pop()
cur.val += pre
pre = cur.val
cur = cur.left
travel(root)
return root
golang
package binaryTree
// 递归-反中序遍历-前序节点值pre完成累加操作
func convertBST1(root *TreeNode) *TreeNode {
var pre int = 0
var travel func(root *TreeNode)
travel = func(root *TreeNode) {
if root == nil {
return
}
travel(root.Right)
root.Val += pre
pre = root.Val
travel(root.Left)
}
travel(root)
return root
}
// 迭代-反中序-前序节点值pre完成累加操作
func convertBST2(root *TreeNode) *TreeNode {
var pre int = 0
var travel func(cur *TreeNode)
travel = func(cur *TreeNode) {
stack := []*TreeNode{}
for cur != nil || len(stack) > 0 {
if cur != nil {
stack = append(stack, cur)
cur = cur.Right
} else {
cur = stack[len(stack)-1]
stack = stack[:len(stack)-1]
cur.Val += pre
pre = cur.Val
cur = cur.Left
}
}
}
travel(root)
return root
}