//669. 修剪二叉搜索树
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func trimBST(root *TreeNode, low int, high int) *TreeNode {
// 终止条件
if root == nil {
return nil
}
// 结点小于左边界值情况,继续遍历该节点的右子树
if root.Val < low {
right := trimBST(root.Right, low, high)
return right
}
// 结点大于右边界值情况,继续遍历该节点的左子树
if root.Val > high {
left := trimBST(root.Left, low, high)
return left
}
root.Left = trimBST(root.Left, low, high)
root.Right = trimBST(root.Right, low, high)
return root
}
func main() {
//k=3
node1, node2, node3, node4 := TreeNode{1, nil, nil}, TreeNode{2, nil, nil}, TreeNode{7, nil, nil}, TreeNode{8, nil, nil}
//k=2
node5, node6 := TreeNode{4, &node1, &node2}, TreeNode{6, &node3, &node4}
//k=1
node7 := TreeNode{5, &node5, &node6}
res := trimBST(&node7, 1, 6)
fmt.Printf("res: %v\n", res) //res: &{5 0xc0000080d8 0xc0000080f0}
}
//108.将有序数组转换为二叉搜索树
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sortedArrayToBST(nums []int) *TreeNode {
var traversal func(nums []int, left, right int) *TreeNode
traversal = func(nums []int, left, right int) *TreeNode { //左闭右闭
//终止条件
if left > right {
return nil
}
//选取中间位置元素做根结点
mid := (left + right) / 2
root := &TreeNode{Val: nums[mid]}
//构造左子树
root.Left = traversal(nums, left, mid-1)
//构造右子树
root.Right = traversal(nums, mid+1, right)
return root
}
root := traversal(nums, 0, len(nums)-1)
return root
}
func main() {
nums := []int{-10, -3, 0, 5, 9}
res := sortedArrayToBST(nums)
fmt.Printf("res: %v\n", res) //res: &{0 0xc000008090 0xc0000080c0}
}
//538.把二叉搜索树转换为累加树
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func convertBST(root *TreeNode) *TreeNode {
pre := 0
var traversal func(cur *TreeNode)
traversal = func(cur *TreeNode) {
//终止条件
if cur == nil {
return
}
//中序遍历二叉搜索树为单调递增序列,现将中序遍历反过来变为单调递减序列
//右
traversal(cur.Right)
//中
cur.Val += pre
pre = cur.Val
//左
traversal(cur.Left)
}
traversal(root)
return root
}
func main() {
//k=3
node1, node2, node3, node4 := TreeNode{1, nil, nil}, TreeNode{2, nil, nil}, TreeNode{7, nil, nil}, TreeNode{8, nil, nil}
//k=2
node5, node6 := TreeNode{4, &node1, &node2}, TreeNode{6, &node3, &node4}
//k=1
node7 := TreeNode{5, &node5, &node6}
res := convertBST(&node7)
fmt.Printf("res: %v\n", res) //res: &{26 0xc0000080d8 0xc0000080f0}
}