那些讓你覺得自己是個傻B的題目集錦(大神的降維打擊合集)
阿新 • • 發佈:2018-12-09
一起過來排好隊,進來捱打
1.Leetcode tag-LinkList 109.convert sorted list to binary search tree
/** * 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) { return RecursionListToBST(head,NULL); } TreeNode* RecursionListToBST(ListNode* head,ListNode *tail){ // linklist is empty if(head==tail) return NULL; // only one node in the tree if(head->next==tail){ TreeNode *root=new TreeNode(head->val); return root; } // search the middle node // excllent code segment need memorize. ListNode *mid=head; ListNode *temp=head; while(temp!=tail && temp->next!=tail){ mid=mid->next; temp=temp->next->next; } TreeNode *root=new TreeNode(mid->val); root->left=RecursionListToBST(head,mid); root->right=RecursionListToBST(mid->next,tail); return root; } }; // 尋找連結串列重點這個真的是棒 ListNode *mid=head; ListNode *temp=head; while(temp!=tail && temp->next!=tail){ mid=mid->next; temp=temp->next->next; }