Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
提交一直无法通过,应该是声明TreeNode时候出现的问题。
/** * 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) { if(num.size() == 0 )return NULL; TreeNode * root; root = BST(num , 0 ,num.size()-1 ); return root; } TreeNode *BST(vector<int> &num, int begin , int end) { if(begin <= end) { int mid = (begin + end)/2; TreeNode *root = new TreeNode(num[mid]); if(begin == end)return root; root->left = BST(num, begin,mid -1); root->right = BST(num, mid +1 ,end); return root; } else return NULL; } };
posted on 2014-03-03 15:25 pengyu2003 阅读(118) 评论(0) 编辑 收藏 举报