//给你一棵二叉搜索树,请你返回一棵 平衡后 的二叉搜索树,新生成的树应该与原来的树有着相同的节点值。
//
// 如果一棵二叉搜索树中,每个节点的两棵子树高度差不超过 1 ,我们就称这棵二叉搜索树是 平衡的 。
//
// 如果有多种构造方法,请你返回任意一种。
//
//
//
// 示例:
//
//
//
// 输入:root = [1,null,2,null,3,null,4,null,null]
//输出:[2,1,3,null,null,null,4]
//解释:这不是唯一的正确答案,[3,1,4,null,2,null,null] 也是一个可行的构造方案。
//
//
//
//
// 提示:
//
//
// 树节点的数目在 1 到 10^4 之间。
// 树节点的值互不相同,且在 1 到 10^5 之间。
//
// Related Topics 二叉搜索树
import java.util.ArrayList;
import java.util.List;
//Java:将二叉搜索树变平衡
public class P1382BalanceABinarySearchTree{
public static void main(String[] args) {
Solution solution = new P1382BalanceABinarySearchTree().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<Integer> seqTree = new ArrayList<>();
public TreeNode balanceBST(TreeNode root) {
order(root);
int right = seqTree.size() - 1;
return plantTree(0, right);
}
public TreeNode plantTree (int left, int right) {
if (left > right) {
return null;
}
int mid = (left + right) / 2;
TreeNode root = new TreeNode(seqTree.get(mid));
root.left = plantTree(left, mid - 1);
root.right = plantTree(mid + 1, right);
return root;
}
public void order(TreeNode root) {
if (root == null) {
return;
}
order(root.left);
seqTree.add(root.val);
order(root.right);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
LeetCode1382【树】:二叉搜索树变平衡树
猜你喜欢
转载自blog.csdn.net/baidu_34209307/article/details/104912472
今日推荐
周排行