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. mac 系统配置(一)

    1.终端颜色配置 文件 .bash_profile下添加环境变量如下: export CLICOLOR=1 export LSCOLORS=gxfxaxdxcxegedabagacad 环境变量生效: ...

  2. Mercedes BENZ C5 SD Connect Xentry Tab Kit Technical Support

    Why MB Star Diagnostic tool is so well-received by thousands of users, its technology and quality is ...

  3. Thinkphp2.1漏洞利用

    thinkphp2.1版本 Google语法: inurl:index.php intext:ThinkPHP 2.1 { Fast & Simple OOP PHP Framework }  ...

  4. jsonProperty

    //说明:界面参数name需要为: employeeName,Json格式的话需要传入:employee_name @JsonProperty("employee_name") p ...

  5. python-URL转jpg图片

    问题描述 有图片地址,可以在网页打开 URL:https://bdfile.bluemoon.com.cn/group2/M00/0A/BA/wKg_HlwzY1SAIdXDAAFyo-ZOLKQ39 ...

  6. DB Intro - MongoDB Relations

    https://www.quackit.com/mongodb/tutorial/mongodb_create_a_relationship.cfm

  7. 内置组件 && vue中强大的缓存机制之keep-alive

    vue中强大的缓存机制之keep-alive 最近在用vue做项目,在切换页面时发现切换回原来的页面无法保存原来的状态. 如A页面需要ajax请求数据,然后切换到B页面做某些事情,再切换回A页面时,A ...

  8. Nmap原理02 - 版本探测介绍(上)

    Nmap原理02 - 版本探测介绍(上) 1.介绍 本文将介绍如何通过修改或添加nmap-service-probes文件来实现对nmap中未知服务的探测,首先介绍服务和版本探测的相关信息,然后介绍服 ...

  9. 数据降维(Dimensionality reduction)

    数据降维(Dimensionality reduction) 应用范围 无监督学习 图片压缩(需要的时候在还原回来) 数据压缩 数据可视化 数据压缩(Data Compression) 将高维的数据转 ...

  10. NBUT 1107——盒子游戏——————【博弈类】

    盒子游戏 Time Limit:1000MS     Memory Limit:65535KB     64bit IO Format: Submit Status Practice NBUT 110 ...