LintCode: Convert Sorted Array to Binary Search Tree With Minimal Height
C++
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param A: A sorted (increasing order) array * @return: A tree node */ TreeNode *sortedArrayToBST(vector<int> &A) { // write your code here if (0 == A.size()) { return NULL; } return buildTree(A, 0, A.size()-1); } TreeNode *buildTree(vector<int> &A, int from, int to) { if (from > to) { return NULL; } int mid = (from+to)/2; TreeNode *node = new TreeNode(A[mid]); node->left = buildTree(A, from, mid-1); node->right = buildTree(A, mid+1, to); return node; } };
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。