LintCode解题思路LintCode解题思路

OJ lintcode 把排序数组转换为高度最小的二叉搜索树

2017-02-19  本文已影响9人  DayDayUpppppp

给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。


image.png
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param A: A sorted (increasing order) array
     * @return: A tree node
     */
    TreeNode *  bst(vector<int > & A ,int beg,int end){
        if(beg>end){
            return NULL;
        }
        if(beg==end){
            TreeNode * node1=new TreeNode(A[end]);
            return node1;
        }
        if(beg==end-1){
            TreeNode * node2=new TreeNode(A[beg]);
            node2->right=new TreeNode(A[end]);
            return node2;
        }

        int mid=(beg+end)/2;
        TreeNode * node =new TreeNode(A[mid]);
        node->left=bst(A,beg,mid-1);
        node->right=bst(A,mid+1,end);
        return node;
    }

    TreeNode *sortedArrayToBST(vector<int> &A) {
        // write your code here
        if(A.size()==0){
            return NULL;
        }
        
        TreeNode * bsttree;
        if(A.size()==1){
            bsttree =new TreeNode(A[0]);
            return bsttree;
        }

        int mid=(0+A.size()-1)/2;
        bsttree=new TreeNode(A[mid]);

        bsttree->left=bst(A,0,mid-1);
        bsttree->right=bst(A,mid+1,A.size()-1);

        return bsttree;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读