设为首页 加入收藏

TOP

LeetCode Convert Sorted List to Binary Search Tree 解题报告
2015-07-20 17:34:49 来源: 作者: 【 】 浏览:2
Tags:LeetCode Convert Sorted List Binary Search Tree 解题 报告
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;
    }
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 4223 Dynamic Programming? (.. 下一篇POJ 1988 Cube Stacking (种类并..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)