[LeetCode] 1382. Balance a Binary Search Tree

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 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.

Example 1:

[LeetCode] 1382. Balance a Binary Search Tree

Input: root = [1,null,2,null,3,null,4,null,null]
Output: [2,1,3,null,null,null,4]
Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.

Example 2:

[LeetCode] 1382. Balance a Binary Search Tree

Input: root = [2,1,3]
Output: [2,1,3]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 1 <= Node.val <= 105

将二叉搜索树变平衡。

给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该原来的树有着相同的节点值。

如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。

如果有多种构造方法,请你返回任意一种。

:力扣(LeetCode)链接:https://leetcode-cn.COM/PRoblems/balance-a-binary-search-tree著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题几乎和108题一样。108题已经给定了一个排好序的数组,这道题对数组没有排序。

既然我们处理的是一个二叉搜索树 BST,那么为了满足平衡的需求,我们首先需要将数组排序,把最中间的那个元素挑出来当做根节点,这样左右子树的节点个数才会平衡。然后我们再用类似108题的分治的做法,分别处理左右子树即可。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 @H_413_126@class Solution {
17     List<TreeNode> sorted = new ArrayList<>();
18 
19     public TreeNode balanceBST(TreeNode root) {
20         inorder(root);
21         return helPEr(0, sorted.size() - 1);
22     }
23 
24     private void inorder(TreeNode root) {
25         if (root == null) {
26             return;
27         }
28         inorder(root.left);
29         sorted.add(root);
30         inorder(root.right);
31     }
32 
33     private TreeNode helper(int start, int end) {
34         if (start > end) {
35             return null;
36         }
37         int mid = start + (end - start) / 2;
38         TreeNode root = sorted.get(mid);
39         root.left = helper(start, mid - 1);
40         root.right = helper(mid + 1, end);
41         return root;
42     }
43 }

 

相关题目

108. Convert Sorted Array to Binary Search Tree

109. Convert Sorted List to Binary Search Tree

1382. Balance a Binary Search Tree

LeetCode 题目总结

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 1382. Balance a Binary Search Tree全部内容,希望文章能够帮你解决[LeetCode] 1382. Balance a Binary Search Tree所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。