您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree

2015-06-01 15:47 155 查看
思路:

方法一:

类似上一题,用自顶向下的方法逐渐构造BST,每次找到midListNode,然后左边的顶点为其左子树,右边的顶点为其右子树。

但是由于链表不是可以随机访问的,每次必须遍历链表来找到中间的节点,时间复杂度比较高。

/**
 * 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 {
private:
    int listLength(ListNode *node) {
        int len = 0;
        while(node) {
            len++;
            node = node->next;
        }
        return len;
    }
    ListNode* buildNthListNode(ListNode *node, int len) {
        while(--len) {
            node = node->next;
        }
        return node;
    }
    TreeNode* buildBST(ListNode *head, int len) {
        if(len == 0) return nullptr;
        if(len == 1) return new TreeNode(head->val);
        TreeNode *root = new TreeNode(buildNthListNode(head, len/2+1)->val);
        root->left = buildBST(head, len/2);
        root->right = buildBST(buildNthListNode(head, len/2+2), (len-1)/2);
        return root;
    }
public:
    TreeNode* sortedListToBST(ListNode* head) {
        return buildBST(head, listLength(head));
    }
};


方法二:


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: