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

【leetcode】Convert Sorted List to Binary Search Tree

时间:2014-06-10 07:17:29      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:leetcode   面试题   algorithm   算法   二叉树   

问题:

给定一个有序链表,生成对应的平衡二叉搜索树。

分析

实现:

TreeNode *buildTree(ListNode* head, ListNode *end){
        if(head == NULL || head == end)
        return NULL;
        ListNode* fast = head;
        ListNode* slow = head;
        //get the middle 
        //notice: != end, not != NULL
        while(fast != end && fast->next != end){
            fast = fast->next->next;
            slow = slow->next;
        }
        TreeNode *root = new TreeNode(slow->val);
        root->left = buildTree(head, slow);
        root->right = buildTree(slow->next, end);
        return root;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        if(head == NULL) 
        return NULL;
        return buildTree(head, NULL);
    }


【leetcode】Convert Sorted List to Binary Search Tree,布布扣,bubuko.com

【leetcode】Convert Sorted List to Binary Search Tree

标签:leetcode   面试题   algorithm   算法   二叉树   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/29590891

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