【Convert Sorted List to Binary Search Tree】cpp

题目:

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) {
            if ( !head ) return NULL;
            // p2 point to the pre node of mid
            ListNode dummy(-1);
            dummy.next = head;
            ListNode *p1 = &dummy, *p2 = &dummy;
            while ( p1 && p1->next && p1->next->next ) { p1 = p1->next->next; p2 = p2->next;}
            // get the mid val & cut off the mid from linked list
            int val = p2->next->val;
            ListNode *h2 = p2->next ? p2->next->next : NULL;
            p2->next = NULL;
            // recursive process
            TreeNode *root = new TreeNode(val);
            root->left = Solution::sortedListToBST(dummy.next);
            root->right = Solution::sortedListToBST(h2);
            return root;
    }
};

tips:

1. 沿用跟数组一样的思路,采用二分查找

2. 利用快慢指针和虚表头技巧;最终的目的是p2指向mid的前驱节点。

3. 生成该节点,并递归生成left和right (这里需要注意传递的是dummy.next而不是head,原因是如果链表中只有一个节点,传head就错误了)

============================================

第二次过这道题,熟练了一些。重点在于求ListNode的中间节点。

/**
 * 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) {
            if (!head) return NULL;
            if (!head->next) return new TreeNode(head->val);
            ListNode* p1 = head;
            ListNode* pre = p1;
            ListNode* p2 = head;
            while ( p2 && p2->next )
            {
                pre = p1;
                p1 = p1->next;
                p2 = p2->next->next;
            }
            TreeNode* root = new TreeNode(p1->val);
            pre->next = NULL;
            root->left = Solution::sortedListToBST(head);
            root->right = Solution::sortedListToBST(p1->next);
            return root;
    }
};

 

posted on 2015-05-16 21:23  承续缘  阅读(159)  评论(0编辑  收藏  举报

导航