- Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
- Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
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 if(head == nullptr) return nullptr; 22 23 ListNode* slow = head; 24 ListNode* fast = head; 25 ListNode* slow_pre = nullptr; 26 while(fast && fast->next){ 27 slow_pre = slow; 28 slow = slow->next; 29 fast = fast->next->next; 30 } 31 if(slow_pre){ 32 slow_pre->next = nullptr; 33 } 34 35 TreeNode* root = new TreeNode(slow->val); 36 if(slow!= head) 37 root->left = sortedListToBST(head); 38 else 39 root->left = nullptr; 40 root->right = sortedListToBST(slow->next); 41 42 return root; 43 } 44 };
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedArrayToBST(vector<int> &num) { int n = num.size(); return sortedArrayToBST(num,0,n-1); } TreeNode* sortedArrayToBST(vector<int>& num,int l,int r){ if(l > r) return nullptr; int mid = l + (r - l+1)/2; //加1保证左子树节点个数不少于右边的节点个数,不加1也是平衡二叉树搜索树,但是无法通过验证 TreeNode* root = new TreeNode(num[mid]); root->left = sortedArrayToBST(num,l,mid - 1); root->right = sortedArrayToBST(num,mid+1,r); return root; } };