LeetCode: Convert Sorted Array to Binary Search Tree
一次过
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *dfs(vector<int> &num, int beg, int len) { 13 if (!len) return NULL; 14 TreeNode *tmp = new TreeNode(num[beg+len/2]); 15 tmp->left = dfs(num, beg, len/2); 16 tmp->right = dfs(num, beg+len/2+1, (len-1)/2); 17 return tmp; 18 } 19 TreeNode *sortedArrayToBST(vector<int> &num) { 20 // Start typing your C/C++ solution below 21 // DO NOT write int main() function 22 int len = num.size(); 23 if (!len) return NULL; 24 return dfs(num, 0, len); 25 } 26 };
C#
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode SortedArrayToBST(int[] nums) { 12 int len = nums.Length; 13 if (len == 0) return null; 14 return dfs(nums, 0, len); 15 } 16 TreeNode dfs(int[] nums, int beg, int len) 17 { 18 if (len == 0) return null; 19 TreeNode tmp = new TreeNode(nums[beg + len / 2]); 20 tmp.left = dfs(nums, beg, len/2); 21 tmp.right = dfs(nums, beg+len/2+1, (len-1)/2); 22 return tmp; 23 } 24 }