Leetcode 109. 有序链表转换二叉搜索树 解题思路及C++实现
方法一:將鏈表轉(zhuǎn)為數(shù)組來處理
解題思路:
因?yàn)殒湵聿缓锰幚?#xff0c;所以我先把鏈表處理成數(shù)組,因?yàn)槭且粋€(gè)升序數(shù)組,所以直接將中間的數(shù)當(dāng)成根結(jié)點(diǎn),然后對(duì)左半部分的節(jié)點(diǎn)和右半部分的節(jié)點(diǎn)進(jìn)行遞歸構(gòu)建二叉搜索樹。
在遞歸函數(shù)中,有兩種情況需要考慮。第一種情況是傳入的left值大于right值,說明是個(gè)null節(jié)點(diǎn);第二種情況是傳入的left==right,說明傳入的區(qū)間只有一個(gè)節(jié)點(diǎn),返回該節(jié)點(diǎn)即可。
?
/*** 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;//先將鏈表轉(zhuǎn)為數(shù)組vector<int> nums;while(head){nums.push_back(head->val);head = head->next;}return getBST(nums, 0, nums.size()-1);}TreeNode* getBST(vector<int>& nums, int l, int r){if(l > r) return NULL;if(l == r){TreeNode* tmp = new TreeNode(nums[l]);return tmp;}int mid = (l + r) / 2;TreeNode* root = new TreeNode(nums[mid]);root->left = getBST(nums, l, mid-1);root->right = getBST(nums, mid+1, r);return root;} };?
方法二:直接對(duì)鏈表進(jìn)行切割
解題思路:
因?yàn)殒湵硎且呀?jīng)排好序的,可使用快慢指針來找到中間的節(jié)點(diǎn),用last指針記錄中間節(jié)點(diǎn)的前一個(gè)節(jié)點(diǎn),然后通過將last的next置為null,將鏈表一分為二。
程序中需要注意的是,當(dāng)函數(shù)輸入的鏈表只有兩個(gè)節(jié)點(diǎn)的時(shí)候,last和slow是指向同一節(jié)點(diǎn)的,需要做一個(gè)條件判斷,然后再遞歸生成左右子樹。
?
/*** 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* slow = head;ListNode* fast = head;ListNode* last = slow;while(fast->next && fast->next->next){last = slow;slow = slow->next;fast = fast->next->next;}fast = slow->next; //需要更新一下fast,不然將last->next置為null之后,slow->next可能也被置為null了(當(dāng)slow和last指向同一個(gè)節(jié)點(diǎn)的時(shí)候)last->next = NULL;TreeNode* tmp = new TreeNode(slow->val);if(slow != last) tmp->left = sortedListToBST(head);tmp->right = sortedListToBST(fast);return tmp;} };?
?
總結(jié)
以上是生活随笔為你收集整理的Leetcode 109. 有序链表转换二叉搜索树 解题思路及C++实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 199. 二叉树的右视
- 下一篇: Leetcode 130. 被围绕的区域