leetcode 11: Convert Sorted Array to Binary Search Tree

来源:互联网 发布:kali linux 查看ip 编辑:程序博客网 时间:2024/04/30 05:48

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

 

/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(num.size()<1) return nullptr;                TreeNode* root = sortRec(num, 0, num.size());                return root;    }    private:    TreeNode * sortRec(vector<int> &num, int start, int end) {        if(start==end) return nullptr;                int mid = start + (end-start)/2;        TreeNode * root = new TreeNode( num[mid] );        root->left = sortRec(num, start, mid);        root->right = sortRec(num, mid+1, end);                return root;    }};


 

 

 

 

/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if( num.size() <= 0) return NULL;                int size = num.size();                return makeSubtree(num, 0, size-1);     }        TreeNode * makeSubtree( vector<int> &num, int low , int high) {        if(low>high) return NULL;                                int mid = (low + high) / 2;        TreeNode * root = new TreeNode( num[mid]);                root->left = makeSubtree( num, low, mid-1);        root->right = makeSubtree( num, mid+1, high);                return root;    }};


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode sortedArrayToBST(int[] num) {        // Start typing your Java solution below        // DO NOT write main() function                if(num.length<1) return null;        return convertRec(num, 0, num.length-1);    }        private TreeNode convertRec(int[] num, int low, int high) {        if(low > high) return null;        int mid = (low+high)>>>1;                TreeNode root = new TreeNode( num[mid]);                root.left = convertRec(num, low, mid-1);        root.right = convertRec(num, mid+1, high);                return root;    }}


原创粉丝点击