首页 > 代码库 > LeetCode :: Convert Sorted Array (link list) to Binary Search Tree [tree]
LeetCode :: Convert Sorted Array (link list) to Binary Search Tree [tree]
1.Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
2.Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这里两道题目,是连在一起的两题,给你一个排好序(升序)的数组或者链表,将它们转为一棵平衡二叉树。假设不排好序的话,一组随机输入的数据,就必须采用RBT或者AVL树,这样操作会变得更复杂,涉及到旋转,但是这里排好序了。所以,只要找到中位数,作为根,然后递归地根据中位数的左、右数列来构建左右子树;
两题的思路都是如上所述, 唯一的区别就是,链表寻找中位数会麻烦一些,需要引入fast、slow两个指针,来寻找中位数,代码如下:
2.link-list
2.Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
这里两道题目,是连在一起的两题,给你一个排好序(升序)的数组或者链表,将它们转为一棵平衡二叉树。假设不排好序的话,一组随机输入的数据,就必须采用RBT或者AVL树,这样操作会变得更复杂,涉及到旋转,但是这里排好序了。所以,只要找到中位数,作为根,然后递归地根据中位数的左、右数列来构建左右子树;
两题的思路都是如上所述, 唯一的区别就是,链表寻找中位数会麻烦一些,需要引入fast、slow两个指针,来寻找中位数,代码如下:
1.Array
class Solution { public: TreeNode *Tree(int left, int right, vector<int> &num){ TreeNode *root = NULL; if (left <= right){ int cen = (left + right) / 2; root = new TreeNode(num[cen]); root->left = Tree(left, cen - 1, num); root->right = Tree(cen + 1, right, num); } return root; } TreeNode *sortedArrayToBST(vector<int> &num) { TreeNode *T = NULL; int N = num.size(); T = Tree(0, N - 1, num); return T; } };
2.link-list
class Solution { public: ListNode *findMid(ListNode *head){ //这里如果链表中只有两个数字,则mid返回的是head->next. if (head == NULL || head -> next == NULL) return head; ListNode *fast, *slow, *pre; fast = slow = head; pre = NULL; while (fast && fast->next){ pre = slow; slow = slow->next; fast = fast->next->next; } pre->next = NULL; return slow; } TreeNode *buildTree(ListNode *head){ TreeNode *root = NULL; ListNode *mid = NULL; if (head){ mid = findMid(head); root = new TreeNode(mid->val); if (head != mid){ root->left = buildTree(head); root->right = buildTree(mid->next); } } return root; } TreeNode *sortedListToBST(ListNode *head) { TreeNode *T; T = buildTree(head); return T; } };
LeetCode :: Convert Sorted Array (link list) to Binary Search Tree [tree]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。