1. 程式人生 > >leetcode-有序連結串列轉換二叉搜尋樹

leetcode-有序連結串列轉換二叉搜尋樹

有序連結串列轉換二叉搜尋樹

這道題需要定義三個指標,通過快慢指標找出中點,作為根節點,然後從頭指標head->指標last這段連結串列再遞迴呼叫sortedListToBST函式,從slow指標下一個節點開始到最後,作為後一個連結串列再進行遞迴呼叫函式sortedListToBST函式。

/**
 * 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==NULL) return
NULL; ListNode* fast=head; ListNode* slow=head; ListNode* last=head; while(fast->next && fast->next->next) { last=slow; slow=slow->next; fast=fast->next->next; } fast=slow->next;
last->next=NULL; TreeNode *cur=new TreeNode(slow->val); if(head!=slow) cur->left=sortedListToBST(head); cur->right=sortedListToBST(fast); return cur; } };