[GeeksForGeeks] Sorted array to balanced BST

本文介绍了一种从已排序数组构建平衡二叉搜索树的方法。通过递归选择中间元素作为根节点,并继续为左右子数组构建子树,最终形成一棵高度平衡的二叉搜索树。该方法的时间复杂度为O(n)。

Given a sorted array. Write a program that creates a Balanced Binary Search Tree using array elements.

If there are n elements in array, then floor(n/2)'th element should be chosen as root and same should be followed recursively.

 

Solution.

1. get the middle element and create root node N.

2. recursively create a balanced BST from the left half of the array and set its root as N's left node.

3. recursively create a balanced BST from the right half of the array and set its root as N's right node.

 

T(n) = 2 * T(n/2) + O(1),  so the time complexity is O(n).

 

 1 class TreeNode {
 2     TreeNode left;
 3     TreeNode right;
 4     int val;
 5     TreeNode(int val){
 6         this.left = null;
 7         this.right = null;
 8         this.val = val;
 9     }
10 }
11 public class Solution {
12     public TreeNode sortedArrayToBalancedBST(int[] a) {
13         if(a == null || a.length == 0){
14             return null;
15         }
16         return toBSTRecursive(a, 0, a.length - 1);
17     }
18     private TreeNode toBSTRecursive(int[] a, int start, int end){
19         if(start > end){
20             return null;
21         }
22         int mid = start + (end - start) / 2;
23         TreeNode node = new TreeNode(a[mid]);
24         node.left = toBSTRecursive(a, start, mid - 1);
25         node.right = toBSTRecursive(a, mid + 1, end);
26         return node;
27     }
28 }

 

转载于:https://www.cnblogs.com/lz87/p/7282826.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值