Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Show Tags

SOLUTION 1:

这个方法比较暴力,每次遍历当前list,找到中间的节点,建立 root,分别使用递归建立左树以及右树,并将左右树挂在root之下。但这个算法会复杂度很高。
建立root次数为N,每次遍历最多N次,最坏为N平方(实际不会这么多)
 public TreeNode sortedListToBST1(ListNode head) {
ListNode fast = head;
ListNode slow = head; ListNode pre = head; if (head == null) {
return null;
} TreeNode root = null;
if (head.next == null) {
root = new TreeNode(head.val);
root.left = null;
root.right = null;
return root;
} // get the middle node.
while (fast != null && fast.next != null) {
fast = fast.next.next; // record the node before the SLOW.
pre = slow;
slow = slow.next;
} // cut the list to two parts.
pre.next = null;
TreeNode left = sortedListToBST1(head);
TreeNode right = sortedListToBST1(slow.next); root = new TreeNode(slow.val);
root.left = left;
root.right = right; return root;
}

SOLUTION 2:

 这个解法使用一个参数来记录当前正在操作的List Node. DFS本身的效果是,从head直到尾部建树,并且将currNode移动到size+1处。

这样可以在1次iterator 我们的List后直接建立树。
这是一种Bottom-up的建树方法。如果我们使用C++,则可以将List Node的指针直接做为入参。我们这里使用了类似的方法,不过,
Java不能使用指针,所以我们自建一个自定义的类,里面只有一个ListNode,这样我们就能方便地修改入参了(好纠结啊,这时主页君就开始怀念起C的指针了),
:)
C++版本可以参见张磊哥哥的解答喔:)
 public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
} int size = ;
ListNode cur = head;
while (cur != null) {
size++;
cur = cur.next;
} CurrNode curNode = new CurrNode(head);
return sortedListToBSTHelp(curNode, size);
} public class CurrNode {
ListNode node; CurrNode(ListNode node) {
this.node = node;
}
} // when the recursion is done, the curr node should point to the node
// which is the next of the block.
public TreeNode sortedListToBSTHelp(CurrNode curr, int size) {
if (size <= ) {
return null;
} TreeNode left = sortedListToBSTHelp(curr, size/); // because we want to deal with the right block.
TreeNode root = new TreeNode(curr.node.val);
curr.node = curr.node.next; TreeNode right = sortedListToBSTHelp(curr, size - - size/); root.left = left;
root.right = right; return root;
}

SOLUTION 3:

这个解法使用一个instance variable 来记录当前正在操作的List Node. DFS本身的效果是,从head直到尾部建树,并且将currNode移动到size+1处。
这样可以在1次iterator 我们的List后直接建立树。
这是一种Bottom-up的建树方法。如果我们使用C++,则可以将List Node直接做为入参来改变之而不需要使用实例变量。
问题是:我们如果可以的话,尽量不要使用实例变量,因为它是各个Method 共享的,所以这个方法存在风险。因为变量有可能被别的方法修改。
 
这个dfs的意思就是 对一个以head 起始的list, size为大小的list建一个树,一个bfs树
并且这个dfs有一个作用 会把指针移动到这个要建的树的下一个位置
 
这样 我们先建立左树,        TreeNode left = dfs(head, size / 2);
经过这一行 cur就移动到了中间
我们建立 一个根         TreeNode root = new TreeNode(curNode.val);

把cur移动到下一个     curNode = curNode.next;
再用递归建立右树      

 
构造我们想要的树 返回根结果
root.left = left;
root.right = right;
return root;
 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode curNode = null; public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
} int size = ;
ListNode cur = head;
while (cur != null) {
size++;
cur = cur.next;
} curNode = head;
return dfs(head, size);
} // Use the size to control.
public TreeNode dfs(ListNode head, int size) {
if (size <= ) {
return null;
} TreeNode left = dfs(head, size / );
TreeNode root = new TreeNode(curNode.val); // move the current node to the next place.
curNode = curNode.next;
TreeNode right = dfs(curNode, size - size / - ); root.left = left;
root.right = right; return root;
}
}

LeetCode: Convert Sorted List to Binary Search Tree 解题报告的更多相关文章

  1. LeetCode: Convert Sorted Array to Binary Search Tree 解题报告

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

  2. 【LeetCode】109. Convert Sorted List to Binary Search Tree 解题报告(Python)

    [LeetCode]109. Convert Sorted List to Binary Search Tree 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id ...

  3. 【LeetCode】108. Convert Sorted Array to Binary Search Tree 解题报告 (Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  4. 【原创】leetCodeOj ---Convert Sorted List to Binary Search Tree 解题报告

    原题地址: https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ 题目内容: Given a sing ...

  5. LeetCode:Convert Sorted Array to Binary Search Tree,Convert Sorted List to Binary Search Tree

    LeetCode:Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in asce ...

  6. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  7. [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树

    Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...

  8. [LeetCode] 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 -- Convert Sorted List to Binary Search Tree

    Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...

随机推荐

  1. Windows2003 SQL2005解决系统Administrator密码不知道的问题

    Windows2003 SQL2005解决系统Administrator密码不知道的问题 今天上班的时候,有个同事说不知道谁设置了开机密码,那台电脑一直没有开机密码的他现在进不了桌面 那台电脑没有光驱 ...

  2. 《Linux内核设计与实现》读书笔记(十四)- 块I/O层

    最近太忙,居然过了2个月才更新第十四章.... 主要内容: 块设备简介 内核访问块设备的方法 内核I/O调度程序 1. 块设备简介 I/O设备主要有2类: 字符设备:只能顺序读写设备中的内容,比如 串 ...

  3. Dynamic CRM 2013学习笔记(二十四)页面保存前进行逻辑验证

    我们有时要验证下页面上的一些逻辑,比如开始时间不能晚于结束时间,不对时不让保存.我们可以在相关的字段事件上处理,但这如果要判断的字段比较多时,就比较麻烦了. 这时候我们就可以利用Form的OnSave ...

  4. 移植到Windows CE 的经验

    Windows CE 是微软早期推出的嵌入式设备和移动设备的开发运行平台,虽然目前移动端几乎都是android和ios的天下,但是,在嵌入式设备领域,Windows CE仍然占有一块地盘.很多用户希望 ...

  5. hive函数 -- split 字符串分割函数

    hive字符串分割函数 split(str, regex) - Splits str around occurances that match regexTime taken: 0.769 secon ...

  6. SQLite 批量insert - 如何加速SQLite的插入操作

    本人翻译, 原文见: http://tech.vg.no/2011/04/04/speeding-up-sqlite-insert-operations/ 我正在开发一个Android程序, 它使用S ...

  7. Activiti 部署流程定义及相关的表(classpath部署、zip部署)

    package com.mycom.processDefinition; import org.activiti.engine.ProcessEngine; import org.activiti.e ...

  8. RFID 仿真/模拟/监控/拦截/检测/嗅探器

    Sound card based RFID sniffer/emulator (Too tired after recon.cx to do draw the schematics better th ...

  9. ASSIC码对照表

    编码对应字符: ✔:\u2714✘:\u2718 <script type="text/javascript"> var aaa = "\u2718" ...

  10. 三步解决EntityFramework Code First中的MissingMethodException错误

    在数据库初始化时运行OnModelCreating的方法中,有时会抛出MissingMethodException异常. 以下三步可解决大部份的出错场景: 在程序包管理器控制台中运行:Uninstal ...