108. Convert Sorted Array to Binary Search Tree (building tree with resursion)
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)的更多相关文章
- 37. leetcode 108. Convert Sorted Array to Binary Search Tree
108. Convert Sorted Array to Binary Search Tree 思路:利用一个有序数组构建一个平衡二叉排序树.直接递归构建,取中间的元素为根节点,然后分别构建左子树和右 ...
- [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 ...
- 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 ...
- 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 ...
- 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.每次更新的 ...
- 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 ...
- [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 ...
- 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. 题目 ...
- 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 ...
- [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 ...
随机推荐
- [转] javascript 判断对象是否存在的10种方法总结
[From] http://www.jb51.net/article/44726.htm Javascript语言的设计不够严谨,很多地方一不小心就会出错.举例来说,请考虑以下情况.现在,我们要判断一 ...
- poj1318 Word Amalgamation 字符串排序(qsort)
Word Amalgamation Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 9794 Accepted: 4701 ...
- nodejs的一些学习
要使用npm的时候,其实是可以直接下载node.js的.参考文档http://www.runoob.com/nodejs/nodejs-npm.html 安装成功之后.判断是否安装成功.是不能直接用n ...
- Exception 'ReflectionException' with message 'Class require does not exist'
记录一下今天遇到的错误 在使用 <?= $form->field($model, 'content')->textarea() ?> 的时候报错 Exception 'Ref ...
- rancher1.X+docker+k8s搭建容器管理集群
一, 环境准备 服务器 Linux k8s-m -.el7.x86_64 #1 SMP Fri Apr 20 16:44:24 UTC 2018 x86_64 x86_64 x86_64 GNU/Li ...
- (转)增加定时检测linux占用内存,及时清理功能
增加定时检测linux占用内存,及时清理功能 原文:http://www.voidcn.com/article/p-wnmannom-boa.html free -m 查看,发现内存跑满了. 再 to ...
- SVM 之 MATLAB 实现代码
MATLAB 中 SVM 实现 直接上代码 main.m %% Initialize data clear, clc, close all; load('data.mat'); y(y == 0) = ...
- Java学习第二十天
1:递归(理解) (1)方法定义中调用方法本身的现象 举例:老和尚给小和尚讲故事,我们学编程 (2)递归的注意事项: A:要有出口,否则就是死递归 B:次数不能过多,否则内存溢出 C:构造方法不能递归 ...
- Python sh模块--------替换subprocess的利器
官方文档有句话"allows you to call any program",并且: helps you write shell scripts in Python by giv ...
- bzoj 5217: [Lydsy2017省队十连测]航海舰队
Description Byteasar 组建了一支舰队!他们现在正在海洋上航行着.海洋可以抽象成一张n×m 的网格图,其中有些位置是" .",表示这一格是海水,可以通过:有些位置 ...