【leetcode】Convert Sorted List to Binary Search Tree

来源:互联网 发布:黑塞矩阵 编辑:程序博客网 时间:2024/05/01 22:52

问题:

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

分析

Convert Sorted Array to Binary Search Tree

实现:

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);    }


0 0
原创粉丝点击