108.Convert Sorted Array to Binary Search Tree(Array; Divide-and-Conquer, dfs)

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

思路:使用二分法,将list的中间节点作为根节点,然后分别处理list左半边及右半边,以此递归。

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.empty()) return NULL;
        TreeNode* root = new TreeNode(0);
        dfs(num,0,num.size()-1,root);          
        return root;
    }
    void dfs(vector<int> &num,int start, int end,TreeNode* treeNode)
    {
        int size = end-start+1;
        if(size == 1)
        {
            treeNode->val = num[start];
            return;
        }
        int mid = size/2 + start;
        treeNode->val = num[mid];      
        treeNode->left = new TreeNode(0);
        dfs(num,start,mid-1,treeNode->left);
        if(mid+1<=end)
        {
            treeNode->right = new TreeNode(0);
            dfs(num,mid+1,end,treeNode->right);
        }  
    }
};

 

posted on 2015-10-03 14:10  joannae  阅读(244)  评论(0编辑  收藏  举报

导航