Wednesday, September 18, 2013

108. Convert Sorted Array to Binary Search Tree (easy)

Q:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

A:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return helper(nums, 0, nums.size());
    }
private:
    TreeNode* helper(vector<int>& nums, int a, int b) // (a, b]
    {
        if(a>=b)
            return NULL;        
        int mid = (a+b)/2;
        TreeNode *root = new TreeNode(nums[mid]);
        root->left = helper(nums,a, mid);
        root->right = helper(nums, mid+1, b);
        return root;
    }    
};


Mistakes:
1:   啊啊啊, damn it.
b 可以是虚的,也可以是实的。  如果用虚的,会比较容易写。



No comments:

Post a Comment