首页 > 代码库 > Leetcode#108 Convert Sorted Array to Binary Search Tree

Leetcode#108 Convert Sorted Array to Binary Search Tree

原题地址

 

对于已排序数组,二分法递归构造BST

 

代码:

 1 TreeNode *buildBST(vector<int> &num, int i, int j) { 2   if (i > j) 3     return NULL; 4          5   int m = (i + j) /2; 6   TreeNode *node = new TreeNode(num[m]); 7   node->left = buildBST(num, i, m - 1); 8   node->right = buildBST(num, m + 1, j); 9         10   return node;11 }12 13 TreeNode *sortedArrayToBST(vector<int> &num) {14   return buildBST(num, 0, num.size() - 1);15 }

 

Leetcode#108 Convert Sorted Array to Binary Search Tree