zoukankan      html  css  js  c++  java
  • [GeeksForGeeks] Sorted array to balanced BST

    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 }
  • 相关阅读:
    树上点对统计poj1741(树的点分治)
    hdu5115(区间dp)
    bestcoder Round#52 1001(最短路+状压dp)
    lightoj1038(期望dp)
    模线性方程组
    hdu2089 数位dp
    poj2955括号匹配 区间DP
    poj1417 带权并查集 + 背包 + 记录路径
    poj1984 带权并查集(向量处理)
    zoj3261 并查集离线处理
  • 原文地址:https://www.cnblogs.com/lz87/p/7282826.html
Copyright © 2011-2022 走看看