b_lc_把二叉搜索树转换为累加树(逆中序遍历 / 迭代)
使BST的每个节点 node 的新值重新等于原树中 >=node.val 的值之和。
递归
func convertBST(root *TreeNode) *TreeNode {
var pre int
var dfs func (root *TreeNode)
dfs = func (root *TreeNode) {
if root == nil {
return
}
dfs(root.Right)
root.Val += pre
pre = root.Val
dfs(root.Left)
}
dfs(root)
return root
}
迭代
func convertBST(root *TreeNode) *TreeNode {
st := []*TreeNode{}
big, cur := 0, root
for len(st) > 0 || cur != nil {
for cur != nil {
st = append(st, cur)
cur = cur.Right
}
top := st[len(st)-1]
st = st[:len(st)-1]
big += top.Val
top.Val = big
cur = top.Left
}
return root
}