标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Tree Depth-first Search
#include <iostream> #include <vector> using namespace std; /** * 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 *sortedArrayToBST(vector<int> &num) { int n = num.size(); if(n ==0) return NULL; if(n==1) return new TreeNode(num[0]); return helpFun(num,0,n-1); } TreeNode * helpFun(vector<int> &num,int lft,int rgt) { if(lft>rgt) return NULL; if(lft==rgt) return new TreeNode(num[lft]); int mid = (lft+rgt)/2; TreeNode * curNode = new TreeNode(num[mid]); curNode->left = helpFun(num,lft,mid-1); curNode->right = helpFun(num,mid+1,rgt); return curNode; } }; int main() { return 0; }
[LeetCode] Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4335674.html