码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Convert Sorted List to Binary Search Tree 解题报告

时间:2014-10-01 23:36:31      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:leetcode解题报告   算法   面试题   递归   二叉树   

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
从给定的有序链表生成平衡二叉树。
解题思路:最容易想到的就是利用数组生成二叉树的方法,找到中间节点作为二叉树的root节点,然后分别对左右链表递归调用分别生成左子树和右子树。时间复杂度O(N*lgN)

AC代码:
public class Solution {
    ListNode getLeftNodeFromList(ListNode head) {
        ListNode next = head;
        ListNode current = head; 
        ListNode pre = head;

        while(next!=null) {
            next = next.next;
            if(next==null) {
                break;
            }
            next = next.next;
            if(next==null) {
                break;
            }
            pre = head;
            head = head.next;
        }
        return pre;
    }
    
    
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) {
            return null;
        }
        if(head.next==null) {
            return new TreeNode(head.val);
        }
        
        ListNode left = getLeftNodeFromList(head);
        ListNode mid = left.next;
        TreeNode root = new TreeNode(mid.val);
        left.next     = null;
        root.left     = sortedListToBST(head);
        root.right    = sortedListToBST(mid.next);
        return root;
    }
}


LeetCode Convert Sorted List to Binary Search Tree 解题报告

标签:leetcode解题报告   算法   面试题   递归   二叉树   

原文地址:http://blog.csdn.net/worldwindjp/article/details/39722643

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!