convert array/list to binary search tree

convert array/list to binary search tree

Array

Not hard, find the middle item, build the node, build left child and right child.Recusive.

 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 ( 0 == n ) {
15             return NULL;
16         }
17         return buildTree(num,0,n-1);
18     }
19     TreeNode* buildTree( vector< int >& num, int left, int right ) {
20         if ( left > right ) {
21             return NULL;
22         }
23         int mid = right+(left-right)/2;
24         TreeNode* node = new TreeNode(num[mid]);
25         node->left = buildTree(num,left,mid-1);
26         node->right = buildTree(num,mid+1,right);
27         return node;
28     }
29 };

list

Not hard too.

 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 ) {
22             return NULL;
23         }
24         int n = 0;
25         ListNode* p = head;
26         while(p) {
27             n++;
28             p = p->next;
29         }
30         return buildTree(head,n);
31     }
32     TreeNode* buildTree(ListNode* head, int n) {
33         if ( !head || n == 0 ) {
34             return NULL;
35         }
36         ListNode* p = head;
37         for( int i = 1; i < (n+1)/2; i++ ) {
38             p = p->next;
39         }
40         TreeNode * t = new TreeNode(p->val);
41         t->left = buildTree(head,(n+1)/2-1);
42         if ( p->next ) {
43             t->right = buildTree(p->next,n-(n+1)/2);
44         }
45         return t;
46     }
47 };

Loading Disqus comments...
Table of Contents