首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s

时间:2015-05-09 11:42:32      阅读:175      评论:0      收藏:0      [点我收藏+]

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


基本思路:

中序遍历的过程,与有序链表的顺序是一一对应的。

采用中序遍历构造进树的构造。

并利用取值范围,确定,根的位置,以及子树的范围。

故需要遍历整个链表,求得总的长度。

链表长度的一半,即为根结点所在位置。 左边则为左子树的取值范围,右边即为右子树的取值范围。

同上,递归应用到左子树,右子树。逐步缩范围,直到叶节点。


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        int size = 0;
        ListNode *p = head;
        while (p) {
            ++size;
            p = p->next;
        }
        
        return helper(head, 0, size-1);
    }
    
    TreeNode *helper(ListNode *&head, int start, int stop) {
        if (start > stop) return 0;
        const int mid = start + (stop-start) / 2;
        TreeNode *left = helper(head, start, mid-1);
        TreeNode *root = new TreeNode(head->val);
        root->left = left;
        head = head->next;
        root->right = helper(head, mid+1, stop);
        return root;
    }
};


Convert Sorted List to Binary Search Tree -- leetcodeGiven a singly linked list where elements are s

原文:http://blog.csdn.net/elton_xiao/article/details/45599721

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!