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
}
posted @ 2021-01-28 00:20  童年の波鞋  阅读(82)  评论(0编辑  收藏  举报