您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree——将链表转换为平衡二叉搜索树 &&convert-sorted-array-to-binary-search-tree——将数列转换为bst

2017-06-15 15:40 585 查看
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.

为了满足平衡要求,容易想到提出中间节点作为树根,因为已排序,所以左右两侧天然满足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==NULL) return NULL;
22         if(head->next==NULL) return new TreeNode(head->val);
23         ListNode *mid=findMid(head);
24         TreeNode *root=new TreeNode(mid->val);
25         root->left=sortedListToBST(head);
26         root->right=sortedListToBST(mid->next);
27         return root;
28     }
29     ListNode *findMid(ListNode *root){
30         if(root==NULL) return NULL;
31         if(root->next==NULL) return root;
32         ListNode *fast,*slow,*pre;
33         fast=root;
34         slow=root;
35         while(fast!=NULL){
36             fast=fast->next;
37             if(fast!=NULL){
38                 fast=fast->next;
39                 pre=slow;
40                 slow=slow->next;
41             }
42         }
43         pre->next=NULL;
44         return slow;
45     }
46 };


convert-sorted-array-to-binary-search-tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

1 /**
2  * Definition for binary tree
3  * struct TreeNode {
4  *     int val;
5  *     TreeNode *left;
6  *     TreeNode *right;
7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8  * };
9  */
10 class Solution {
11 public:
12     TreeNode *sortedArrayToBST(vector<int> &num) {
13         int n=num.size();
14         if(n<1) return NULL;
15
16         return findMid(num,0,n-1);
17     }
18     TreeNode *findMid(vector<int> &num, int l,int r){
19         if(l>r) return NULL;
20         int mid=(l+r+1)/2;
21         TreeNode *root=new TreeNode(num[mid]);
22         root->left=findMid(num,l,mid-1);
23         root->right=findMid(num,mid+1,r);
24         return root;
25     }
26 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐