【Leetcode长征系列】Convert Sorted Array to Binary Search Tree
来源:互联网 发布:扬州大学网络教学凭条 编辑:程序博客网 时间:2024/05/16 10:33
原题:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
【复习时间】:平衡二叉树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。常用算法有红黑树、AVL、Treap、伸展树等。在平衡二叉搜索树中,我们可以看到,其高度一般都良好地维持在O(log2n),大大降低了操作的时间复杂度。
参考链接:www.cppblog.com/cxiaojia/archive/2012/08/20/187776.html
思路:一开始想的过于复杂了,以为涉及到了zigzag之类的东西。但其实这道题用递归就可以完成。其中有很多需要注意的细节:
1. TreeNode *root=NULL;指针一定要初始化不然一定会runtime error!。
2. buildBST(vector<int> &num, TreeNode *&root, int left, int right) 传递树节点的指针时必须还有个引用符号,即*&,光有*或是光有&都是传递不了指针的,主函数最后的返回结果会成为空。
代码:
/** * 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) { TreeNode *root=NULL; if(num.size()>0) buildBST(num, root, 0, num.size()-1); return root; } void buildBST(vector<int> &num, TreeNode *&root, int left, int right){ if(left>right) return; int mid = (left+right)/2; root = new TreeNode(num[mid]); buildBST(num, root->left, left, mid-1); buildBST(num, root->right, mid+1, right); }};
0 0
- 【Leetcode长征系列】Convert Sorted Array to Binary Search Tree
- 【Leetcode长征系列】Convert Sorted List to Binary Search Tree
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- 【LeetCode】convert-sorted-link-to-binary-search-tree & convert-sorted-array-to-binary-search-tree
- Leetcode - Tree - Convert Sorted Array to Binary Search Tree
- *(leetcode) Convert Sorted Array to Binary Search Tree (tree)
- LeetCode[Tree]: Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted Array to Binary Search Tree
- leetcode 11: Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- C语言学习-变量内存分析总结
- 窗体的扩展样式和其值
- 让securecrt记录更多的屏幕信息
- XCODE快速缩进
- UVA 11292-Dragon of Loowater (思维)
- 【Leetcode长征系列】Convert Sorted Array to Binary Search Tree
- JAVA 长整型转换为IP地址的方法
- hdu 1050 Moving Tables
- eclipse UTF-8
- LeetCode 119 Pascal's Triangle II
- 8.查询数据库中的数据,并显示出来
- maven的搭建安装
- 中期工作总结和下期计划
- c# winform 中导入Excel 的问题 !