标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *build(vector<int> &num, int l, int r) { if (l <= r) { int m = (l+r)/2; TreeNode *root = new TreeNode(num[m]); root->left = build(num,l,m-1); root->right = build(num,m+1,r); return root; } else { return NULL; } } TreeNode *sortedArrayToBST(vector<int> &num) { int n = num.size(); if (n == 0) return 0; return build(num,0,n-1); } };
Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/SpeakSoftlyLove/p/5216158.html