标签:leetcode 平衡二叉树 查找二叉树 二分法 dfs
problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Tree Depth-first Searchthinking:
(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
标签:leetcode 平衡二叉树 查找二叉树 二分法 dfs
原文地址:http://blog.csdn.net/hustyangju/article/details/45217537