From 89c9044bf984ad638d07932f3b9ebe91e2e7589d Mon Sep 17 00:00:00 2001 From: xiaojun <13589818805@163.com> Date: Thu, 23 Jun 2022 15:36:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=881382.=20=E5=B0=86?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E5=8F=98=E5=B9=B3?= =?UTF-8?q?=E8=A1=A1=EF=BC=89=E7=9A=84go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1382.将二叉搜索树变平衡.md | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/problems/1382.将二叉搜索树变平衡.md b/problems/1382.将二叉搜索树变平衡.md index 57231ec4..7c7f8484 100644 --- a/problems/1382.将二叉搜索树变平衡.md +++ b/problems/1382.将二叉搜索树变平衡.md @@ -123,6 +123,46 @@ class Solution: ``` Go: +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func balanceBST(root *TreeNode) *TreeNode { + // 二叉搜索树中序遍历得到有序数组 + nums := []int{} + // 中序递归遍历二叉树 + var travel func(node *TreeNode) + travel = func(node *TreeNode) { + if node == nil { + return + } + travel(node.Left) + nums = append(nums, node.Val) + travel(node.Right) + } + // 二分法保证左右子树高度差不超过一(题目要求返回的仍是二叉搜索树) + var buildTree func(nums []int, left, right int) *TreeNode + buildTree = func(nums []int, left, right int) *TreeNode { + if left > right { + return nil + } + mid := left + (right-left) >> 1 + root := &TreeNode{Val: nums[mid]} + root.Left = buildTree(nums, left, mid-1) + root.Right = buildTree(nums, mid+1, right) + return root + } + travel(root) + return buildTree(nums, 0, len(nums)-1) +} + +``` + JavaScript: ```javascript var balanceBST = function(root) {