Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
哎,又是被指针坑了,指针作为函数的参数传递时,在函数体内可以修改指针所指的内容,但是不有修改指针本身,所以一时是运行时错误,这里要用指针的引用TreeNode *&,问题得解。算法没什么好说的,递归求解,每次取传入列表的中位数为节点的值。
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 void buildTree(TreeNode *&root, vector<int> &num, int l, int h) { 13 if (l <= h) { 14 int mid = (l + h) / 2; 15 root = new TreeNode(num[mid]); 16 buildTree(root->left, num, l, mid - 1); 17 buildTree(root->right, num, mid + 1, h); 18 } 19 } 20 21 TreeNode *sortedArrayToBST(vector<int> &num) { 22 if (num.size() < 1) { 23 return NULL; 24 } 25 TreeNode *root; 26 buildTree(root, num, 0, num.size() - 1); 27 return root; 28 } 29 };