leetcode || 108、Convert Sorted Array to Binary Search Tree

来源:互联网 发布:篮球记分牌软件 编辑:程序博客网 时间:2024/05/17 04:05

problem:

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

Hide Tags
 Tree Depth-first Search
题意:将一个递增的序列 转换成一棵 平衡查找二叉树

thinking:

(1)平衡二叉树的概念:左右子树的高度差最大不能超过1,查找二叉树的概念:左孩子<父节点<右孩子

(2)二分法递归构造二叉树

(3)模板函数解决形参类型vector<int>::iterator 太长,书写不方便

code:

class Solution {  public:      TreeNode *sortedArrayToBST(vector<int> &num) {          if(num.size()==0)              return NULL;          return make(num.begin(),num.end());                }      template<class it>      TreeNode *make(it first,it last)      {          if(first==last)              return NULL;          it loc = first+(last-first)/2;          TreeNode *node = new TreeNode(*loc);          node->left=make(first,loc);          node->right=make(loc+1,last);          return node;      }  };


0 0