Day23 Golang (二叉树) 669. 修剪二叉搜索树 108.将有序数组转换为二叉搜索树 538.把二叉搜索树转换为累加树

//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}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值