[Leetcode] Convert sorted list to binary search tree 將排好的鏈表轉成二叉搜索樹
---恢復內容開始---
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
題目要求:轉成高度平衡的二叉搜索樹。
高度平衡的二叉搜索樹:i)左子樹和右子樹的高度之差的絕對值不超過1; ii)樹中的每個左子樹和右子樹都是AVL樹; iii)每個節點都有一個平衡因子(balance factor bf),任一節點的平衡因子是1,0,-1.(每個節點的平衡因子等於右子樹的高度減去左子樹的高度) .
方法一:使用快慢指針
思路:若是一升序的數組,則取中間元素,作為根節點,然後以此方法分別去構成處左右子樹。但鏈表沒有辦法直接訪問其中間的結點,怎麽辦?可以通過快慢指針的方式,當快指針到鏈表結尾時,慢指針剛好到鏈表的中間來實現找到中間結點的目的。然後用遞歸的方法構造樹。代碼如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 /** 10 * Definition for binary tree 11 * struct TreeNode { 12 * int val; 13 * TreeNode *left; 14 * TreeNode *right;15 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 * }; 17 */ 18 class Solution { 19 public: 20 TreeNode *sortedListToBST(ListNode *head) 21 { 22 if(head==NULL) return NULL; 23 if(head->next==NULL) return new TreeNode(head->val); 24 25 ListNode *fast=head;26 ListNode *slow=head; 27 ListNode *preSlow=NULL; 28 29 while(fast&&fast->next) 30 { 31 preSlow=slow; 32 slow=slow->next; 33 fast=fast->next->next; 34 } 35 36 TreeNode *root=new TreeNode(slow->val); 37 preSlow->next=NULL; 38 root->left=sortedListToBST(head); 39 root->right=sortedListToBST(slow->next); 40 41 return root; 42 43 } 44 };
代碼中值得註意的:一、只有一個結點時返回值的寫法;二、使用快慢指針時,前半段要比後半段多;三、鏈表分成兩條時,註意在結尾壓入NULL,形成兩條。
方法二:使用結點的個數一分為二
可以按照類似中序遍歷的做法,首先,創建當前節點的左孩子,然後創建當前節點,將該節點的left指針指向之前創建好的左孩子,然後創建右孩子,以這樣的順序,每次新創建的節點都對應單鏈表的順序遍歷中當前位置的節點,因此,用一個全局遍歷表示當鏈表,在遞歸過程中不斷修改當前單鏈表的指針,使每次創建的節點與單鏈表頭節點對應。這裏的start和end使用來作為終止條件
class Solution { public: TreeNode *sortedListToBST(ListNode *head) { int len=0; ListNode *node=head; while(node !=NULL) { node=node->next; len++; } return rebuildBST(head,0,len-1); } TreeNode *rebuildBST(ListNode *&node,int start,int end) { if(start>end) return NULL; //防止內存泄漏 mid=start+(end-start)/2;但是測試{1,3}(為偶數)用例通不過 int mid=(start+end+1)>>1; TreeNode *leftChild=rebuildBST(node,start,mid-1); TreeNode *parent=new TreeNode(node->val); parent->left=leftChild; node=node->next; parent->right=rebuildBST(node,mid+1,end); return parent; } };
[Leetcode] Convert sorted list to binary search tree 將排好的鏈表轉成二叉搜索樹