leetcode 108.Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

给一个升序数组,让重建一个AVL二叉搜索树

思路:
AVL就是左右子树高度差不能>1
N h N_{h} Nh表示高度为h的node数

N h − 1 , N h − 2 N_{h-1}, N_{h-2} Nh1,Nh2表示左子树和右子树(不按顺序)

N h = 1 + N h − 1 + N h − 2 > 2 N h − 2 N_{h} = 1 + N_{h-1} + N_{h-2} > 2 N_{h-2} Nh=1+Nh1+Nh2>2Nh2
其中 N h N_{h} Nh表示高度为h的node数

为了保持平衡,尽量左子树右子树node数一样

而已经知道BST中序遍历得到的是升序数组
中序遍历顺序:左子树,root,右子树

所以取中间元素作root
然后递归

//0ms
public TreeNode sortedArrayToBST(int[] nums) {
    
    return buildTree(nums, 0, nums.length-1);
}

TreeNode buildTree(int[] nums, int start, int end) {
    if(start > end) return null;
    
    int rootIdx = start + (end - start) / 2;
    TreeNode root = new TreeNode(nums[rootIdx]);
    root.left = buildTree(nums, start, rootIdx-1);
    root.right = buildTree(nums, rootIdx+1, end);
    
    return root;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值