首页 > 代码库 > [Leetcode][BST][Convert Sorted Array to Binary Search Tree]

[Leetcode][BST][Convert Sorted Array to Binary Search Tree]

把一个排好序的vector转换为一颗二分查找树。

很简单的题目,递归即可,保证边界不要出错。

 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     typedef vector<int>::iterator Iter;13     TreeNode *toBST(Iter begin, Iter end) {14         int n = end - begin;15         if (n <= 0) {16             return NULL;17         }18         int pos = n / 2;19         TreeNode *node = new TreeNode(*(begin + pos));20         node->left = toBST(begin, begin + pos);21         node->right = toBST(begin + pos + 1, end);22         return node;23     }24     TreeNode *sortedArrayToBST(vector<int> &num) {25         return toBST(num.begin(), num.end());26     }27 };

一次AC。