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

Solution: O(n) , space: 栈空间O(logn)(from recusrsive expression)加上结果的空间O(n) : O(n) (good reference: https://blog.csdn.net/linhuanmars/article/details/23904883)

  • sorting array for BST(left < root < right)
  • start from middle node and let left part as left subtree , right as well
  • recursion with returing root-- pattern:
TreeNode root = new TreeNode(nums[m]);
root.left = helper(nums, l, m-1);
root.right = helper(nums, m+1, r);
return root;

Totally

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
return helper(nums, 0, nums.length-1);
}
// //recursive with return,
TreeNode helper(int[] nums, int l, int r){
if(l > r) return null;
int m = (r-l)/2 + l;
TreeNode root = new TreeNode(nums[m]);
root.left = helper(nums, l, m-1);
root.right = helper(nums, m+1, r);
return root;
}
}

Follow up questions: 109 convert sorted list to BST

Given a singly linked list 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 linked list: [-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

Solution:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//one way: get middle of linkedlist (slow, fast)
//another way: use preorder(left, root, right), need get the number of anodes in the list
//1: int m = (r-l)/2 + l; 2: //node just copy the reference
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
ListNode cur = head;
int m = 0;
while(cur != null){
m++;
cur = cur.next;
}
List<ListNode> list = new ArrayList<>();
list.add(head);
return helper(list, 0, m-1);
}
TreeNode helper(List<ListNode> list, int l, int r){ //node just copy the reference
if(l>r) return null; int m = (r-l)/2 + l;
TreeNode left = helper(list, l, m-1);//
TreeNode root = new TreeNode(list.get(0).val);
root.left = left;
list.set(0, list.get(0).next);
root.right = helper(list, m+1, r);
return root;
} }

Solution 2: get middle of list (slow and fast)

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
return BST(head, null);
}
public TreeNode BST(ListNode head, ListNode tail) {
if(head == tail) return null; ListNode slow = head;
ListNode fast = head;
while(fast!=tail&&fast.next!=tail) { //tail
fast = fast.next.next;
slow = slow.next;
}
TreeNode node = new TreeNode(slow.val);
node.left = BST(head, slow);
node.right = BST(slow.next, tail);
return node;
}
}

108. Convert Sorted Array to Binary Search Tree (building tree with resursion)的更多相关文章

  1. 37. leetcode 108. Convert Sorted Array to Binary Search Tree

    108. Convert Sorted Array to Binary Search Tree 思路:利用一个有序数组构建一个平衡二叉排序树.直接递归构建,取中间的元素为根节点,然后分别构建左子树和右 ...

  2. [LeetCode] 108. Convert Sorted Array to Binary Search Tree ☆(升序数组转换成一个平衡二叉树)

    108. Convert Sorted Array to Binary Search Tree 描述 Given an array where elements are sorted in ascen ...

  3. 108. Convert Sorted Array to Binary Search Tree 109. Convert Sorted List to Binary Search Tree -- 将有序数组或有序链表转成平衡二叉排序树

    108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascendin ...

  4. LeetCode 108. Convert Sorted Array to Binary Search Tree (将有序数组转换成BST)

    108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascendin ...

  5. leetcode 108. Convert Sorted Array to Binary Search Tree 、109. Convert Sorted List to Binary Search Tree

    108. Convert Sorted Array to Binary Search Tree 这个题使用二分查找,主要要注意边界条件. 如果left > right,就返回NULL.每次更新的 ...

  6. 108. Convert Sorted Array to Binary Search [Python]

    108. Convert Sorted Array to Binary Search Given an array where elements are sorted in ascending ord ...

  7. [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. Fo ...

  8. 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. 题目 ...

  9. Leetcode No.108 Convert Sorted Array to Binary Search Tree(c++实现)

    1. 题目 1.1 英文题目 Given an integer array nums where the elements are sorted in ascending order, convert ...

  10. [LeetCode&Python] Problem 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. Fo ...

随机推荐

  1. PIE SDK地图平移校正

    地图平移校正,当加载两幅空间参考一样的影像,其中一幅影像有点偏移,这时就以另一幅影像为基准将其进行平移校正,然后保存,再次加载就不会出现偏移了. 下面来介绍下实现的主要代码: 首先通过选中目录树中的要 ...

  2. git 填坑之 git 暂存区忽略文件

    今天修改公司项目文件的时候,发现被修改的文件的始终不显示已经被修改. 本来是想要把 KWh 改成 kWh,然后执行 git status 后,没有文件修改记录: 开始分析究竟是因为什么导致的这样诡异的 ...

  3. android上最多有多少个http连接?

    1.使用HttpUrlConnection能有几个 测试机器版本是5.1.1 个数 网络连接是否报错 写文件是否报错  1024  A/art: art/runtime/indirect_refere ...

  4. ELK 插件(一) ---- head

    一, 插件介绍 01, ElasticSearch Head是什么? ElasticSearch Head是集群管理.数据可视化.增删查改.查询语句可视化工具.可以对集群进行傻瓜式操作.你可以通过插件 ...

  5. select简单示例,有注释

    全部都在代码中: import select import socket import queue """ 简单的select 实现echo server 个人理解: s ...

  6. 水平垂直居中方案与flexbox布局

    [前端攻略]最全面的水平垂直居中方案与flexbox布局   最近又遇到许多垂直居中的问题,这是Css布局当中十分常见的一个问题,诸如定长定宽或不定长宽的各类容器的垂直居中,其实都有很多种解决方案.而 ...

  7. 在lua中解决if else switch问题

    之前写过一个c#版本的使用字典去解决switch问题  http://www.cnblogs.com/sanyejun/p/7806210.html 现在用写lua版本的 function Main( ...

  8. 白话SpringCloud | 第五章:服务容错保护(Hystrix)

    前言 前一章节,我们知道了如何利用RestTemplate+Ribbon和Feign的方式进行服务的调用.在微服务架构中,一个服务可能会调用很多的其他微服务应用,虽然做了多集群部署,但可能还会存在诸如 ...

  9. 利用pandas生成csv文件

    # -*- coding:UTF-8 -*- import json from collections import OrderedDict with open('dns_status.json',' ...

  10. Jmeter压力测试入门操作

    Jmeter压力测试入门   1. 前言 Jmeter 是Apache组织开发的基于Java的压力测试工具,开源并且支持多个操作系统,是一款很好的HTTP测试工具.本篇文章主要的目的是帮助没有接触过J ...