题解 | #将升序数组转化为平衡二叉搜索树#
将升序数组转化为平衡二叉搜索树
http://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d
注意中点的取值,以及终止条件
class Solution { public: /** * * @param num int整型vector * @return TreeNode类 */ TreeNode *sortedArrayToBST(vector<int> &num) { if (num.size() < 1) return nullptr; TreeNode *root = preOrder(num, 0, num.size() - 1); return root; } TreeNode *preOrder(vector<int> &num, int left, int right) { if (left > right) return nullptr;//注意是,左大于右 // 1. 找到中间节点 int mid = left + (right - left + 1) / 2;//注意这个中点的取值方法 // 2. 递归构建左右 TreeNode *root = new TreeNode(num[mid]); root->left = preOrder(num, left, mid - 1); root->right = preOrder(num, mid + 1, right); return root; } };
算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结