leetcode update

This commit is contained in:
gameloader 2024-06-26 14:31:07 +08:00
parent 4b5e5c64ab
commit 6219154e4e

View File

@ -8035,3 +8035,72 @@ func rightFirst(root *TreeNode, pass int)int{
```
## day121 2024-06-26
### 1382. Balance a Binary Search Tree
Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
![0626MDuY3BC9YtnG](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/0626MDuY3BC9YtnG.png)
### 题解
本题要求将二叉搜索树转换为二叉平衡搜索树, 这就是在二叉平衡树新插入节点时常用的平衡操作. 但在本题中不需要使用常规的二叉平衡树中常用的左旋, 右旋等操作, 原因是二叉平衡树中常用的平衡操作是在插入一个新节点时用于调整树的平衡性的, 所以最多只需两次旋转即可调整平衡. 但在本题中, 树的不平衡性可能非常大, 且我们只需要在原来的树的基础上获得一棵新树. 只需考虑构造出一棵平衡树即可, 不需要考虑多次调整的情况.
因此遍历当前整棵二叉搜索树, 将树中的值从小到大保存到数组中, 二分法构造一棵新的平衡树就能得到最终结果.
### 代码
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func balanceBST(root *TreeNode) *TreeNode {
nums := []*TreeNode{}
nums = traverse(root)
length := len(nums)
root = build(nums, length)
return root
}
func traverse(root *TreeNode)[]*TreeNode{
if root.Left == nil && root.Right == nil{
return []*TreeNode{root}
}
left := []*TreeNode{}
if root.Left != nil{
left = traverse(root.Left)
}
right := []*TreeNode{}
if root.Right != nil{
right = traverse(root.Right)
}
left = append(left, root)
left = append(left, right...)
return left
}
func build(nums []*TreeNode, leng int) *TreeNode{
if leng == 0{
return nil
}else if leng == 1{
nums[0].Left = nil
nums[0].Right = nil
return nums[0]
}else{
leftRoot := build(nums[0:leng/2], leng/2)
rightRoot := build(nums[leng/2+1:], leng-(leng/2+1))
root := nums[leng/2]
root.Left = leftRoot
root.Right = rightRoot
return root
}
return nil
}
```