首页 > 其他 > 详细

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

时间:2015-04-23 10:58:50      阅读:178      评论:0      收藏:0      [点我收藏+]

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;
      }
  };


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

原文:http://blog.csdn.net/hustyangju/article/details/45217537

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!