LeetCode538. 把二叉搜索树转换为累加树Golang版
1. 问题描述
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。



2. 思路
- 逆中序遍历,用prev记录上一个节点的值
- 执行pop.Val += prev.Val
3. 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func convertBST(root *TreeNode) *TreeNode {
// var sum int
if root == nil {
return root
}
var stack []*TreeNode
// prev必须初始化0
prev := &TreeNode{}
node := root
for node != nil || len(stack) > 0 {
for node != nil {
stack = append(stack, node)
node = node.Right
}
pop := stack[len(stack) - 1]
pop.Val += prev.Val
prev = pop
stack = stack[:len(stack) - 1]
node = pop.Left
}
return root
}
本文介绍了如何使用Golang实现将二叉搜索树转换为累加树的算法,通过逆序遍历的方式,计算每个节点值为其父节点以上所有大于或等于其值的节点之和。核心思路是利用栈来辅助操作。
757

被折叠的 条评论
为什么被折叠?



