首页 > 代码库 > 【leetcode】Convert Sorted Array to Binary Search Tree (easy)
【leetcode】Convert Sorted Array to Binary Search Tree (easy)
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
有序数组变二叉平衡搜索树,不难,递归就行。每次先序建立根节点(取最中间的数),然后用子区间划分左右子树。
一次就AC了
注意:new 结构体的时候对于
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};
要用 TreeNode * root = new TreeNode(123); 与构造函数的形式要一致。
#include <iostream>#include <vector>#include <algorithm>#include <queue>#include <stack>using namespace std;//Definition for binary treestruct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: TreeNode *sortedArrayToBST(vector<int> &num) { if(num.empty()) { return NULL; } int nr = num.size()/2; TreeNode * root = new TreeNode(num[nr]); vector<int> numl(num.begin(), num.begin() + nr); vector<int> numr(num.begin() + nr + 1, num.end()); root->left = sortedArrayToBST(numl); root->right = sortedArrayToBST(numr); return root; }};int main(){ Solution s; vector<int> num; num.push_back(1); num.push_back(2); num.push_back(3); num.push_back(4); num.push_back(5); num.push_back(6); num.push_back(7); TreeNode * ans = s.sortedArrayToBST(num); return 0;}
【leetcode】Convert Sorted Array to Binary Search Tree (easy)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。