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 *sortedArrayToBST(vector<int>&num) 13 { 14 TreeNode *root=NULL; 15 if(num.size()) 16 DFS(root,num,0,num.size()-1); 17 return root; 18 } 19 void DFS(TreeNode *(&root),vector<int> num,int low,int high) 20 { 21 int mid=(low+high)/2; 22 int value=num[mid]; 23 root=new TreeNode(value); 24 if(low<mid) 25 DFS(root->left,num,low,mid-1); 26 if(high>mid) 27 DFS(root->right,num,mid+1,high); 28 } 29 };