Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
对于树来说,自顶向下的递归是很好控制的,自底向上的递归就很容易让脑神经打结了。本来想仿照排序二叉树的中序遍历,逆向地由数组构造树,后来发现这样做需要先确定树的结构,不然会一直递归下去,不知道左树何时停止。
代码:
TreeNode *addNode(vector<int> &num, int start, int end){ if(start > end) return NULL; int mid = (start + end)/2; TreeNode *root = new TreeNode(num[mid]); root->left = addNode(num, start, mid-1); root->right = addNode(num, mid+1, end); return root; } TreeNode *sortedArrayToBST(vector<int> &num) { return addNode(num, 0, num.size()-1); }