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. Java swing中的keyListener使用事例

    最近在学习Java swing,写了一个域内聊天室,实现用户登录ip,端口号之后,进入聊天窗口聊天: 通过菜单条增加了几个功能,边框,字体,颜色和文件传输.风格里的样式都可以通过自己选择来设置. 介绍 ...

  2. C#生成二維碼(ThoughtWorks.QRCode)

    本人使用的是ThoughtWorks.QRCode.dll,在網上可以下載,但要注意dll文件的完整性和準確性,本人之前下載的dll就是不正確導致調試時出現錯誤. 以下為cs文件代碼: using S ...

  3. 2.Exadata 硬件体系结构

    Exadata 硬件加构: 高性能,低成本 冗余 线性扩展 ,具有超强性能,开箱即用         例 2-2的满配: 8台数据服务器组成(2C 6核) (3-2是10核, 4-2,5-2 是12核 ...

  4. TCP/IP协议分为哪四层,具体作用是什么。

    TCP/IP通讯协议采用了4层的层级结构,每一层都呼叫它的下一层所提供的网络来完成自己的需求.这4层分别为: 应用层:应用程序间沟通的层,如简单电子邮件传输(SMTP).文件传输协议(FTP).网络远 ...

  5. do while循环

    do while循环: 语法格式: do{ 循环体 }while(循环条件); 执行流程: 先执行循环体,然后判断条件,当条件为true时,则继续执行循环体,然后再判断条件... 一直到循环条件为fa ...

  6. 接口隔离原则(Interface Segregation Principle)ISP

    using System; using System.Collections.Generic; using System.Text; namespace InterfaceSegregationPri ...

  7. AutoFac之 Named and Keyed 方式注入

    AutoFac是.net framework下一个高效的ioc容器,传说中的效率最快(我偷偷看了几篇测试博文,确实这个容器的效率遥遥领先). 好了废话不多说,AutoFac的使用方式请看:http:/ ...

  8. IE Error: '__doPostBack' is undefined 问题解决

    突然遇到个很奇怪的BUG,翻页控件,其他浏览器一切正常,IE无法翻页,会提示 '__doPostBack' is undefined 后来搜索发现: [原文發表地址] Bug and Fix: ASP ...

  9. opensuse install oracle 11gR2 Error in invoking target 'agent nmhs' of makefile '../ins_emagent.mk'

    转自 http://blog.csdn.net/ly5156/article/details/6647563 遭遇Error in invoking target 'agent nmhs' of ma ...

  10. 信号和槽:Qt中最差劲的创造

    不要被这个标题唬住了,实际上我是非常认可Qt的.在C++实现的开源产品中没有哪一个的API风格比得上Qt,拥有高度一致性,符合常识,符合直觉,几乎不用学就可以直接上手.或许是由于我们摆脱不了马太效应的 ...