首页 > 代码库 > Leetcode:convert_sorted_array_to_binary_search_tree

Leetcode:convert_sorted_array_to_binary_search_tree

一、     题目

将一个排好序的数组转换成一个二叉搜索树。

二、     分析

   BST的中序遍历是一个sorted-array,再构造回去成一个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) {
	    return addNode(num, 0, num.size()-1);
	   }
	   TreeNode *addNode(vector<int> &num, int start, int end){
	    if(start > end) return NULL;
	    
	    int mid = (start + end)/2;
	    TreeNode *root = new TreeNode(num[mid]);
	    root->left = addNode(num, start, mid-1);
	    root->right = addNode(num, mid+1, end);
	    return root;
	   }
};


Leetcode:convert_sorted_array_to_binary_search_tree