109. Convert Sorted List to Binary Search Tree
来源:互联网 发布:淘宝联盟贷款入口 编辑:程序博客网 时间:2024/06/06 05:26
Q
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/?tab=Description
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
A
法一
思想同数组convert sorted array to binary search tree,只是链表只能顺序遍历。
struct TreeNode* toBST(struct ListNode* head, int n){ if (n == 0) { return NULL; } struct ListNode *p; struct TreeNode *node; int mid; int i; p = head; mid = n/2; for (i = 0; i < mid; ++i) { p = p->next; } node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); node->val = p->val; node->left = toBST(head, mid); p = p->next; node->right = toBST(p, n-mid-1); return node; }struct TreeNode* sortedListToBST(struct ListNode* head) { if (head == NULL) { return NULL; } int n = 0; struct ListNode* p; p = head; while(p != NULL) { ++n; p = p->next; } return toBST(head, n);}
方法二,模拟树的中序遍历,自底向上建树,注意这里指向指针的指针
C语言
struct TreeNode *toBST(struct ListNode **head, int n) { if(n == 0) { return NULL; } /* int mid; struct TreeNode *node; node = (struct TreeNode *)malloc(sizeof(struct TreeNode)); node->left = toBST(head, mid); node->val = head->val; head = head->next; node->right = toBST(head, n-mid-1); return node; */ int mid; struct TreeNode *c, *p; //struct ListNode *h; mid = n/2; c = toBST(head, mid); p = (struct TreeNode *)malloc(sizeof(struct TreeNode)); p->val = (*head)->val; p->left = c; *head = (*head)->next; p->right = toBST(head, n-mid-1); return p;}struct TreeNode* sortedListToBST(struct ListNode* head) { if (head == NULL) { return NULL; } int n = 0; struct ListNode* p; p = head; while(p != NULL) { ++n; p = p->next; } return toBST(&head, n);}
0 0
- Tree-----109. Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- convert sorted list to binary search tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree
- 隐藏标题栏无效和点击按钮Toast不显示
- iOS开发 实现界面跳转翻页等效果
- SQL Server 表分区实战系列(文章索引)
- 页面跳转+把数据库中查出的内容显示在该页面上
- Java类的初始化顺序
- 109. Convert Sorted List to Binary Search Tree
- SQL Server 备份和还原全攻略
- Android 关于对某个 view 的截图和截图之后再对 view的图片进行高斯模糊效果
- 数组的属性修饰符到底用strong还是copy?
- DW透明边框代码
- Max Sum
- 风浪依旧
- iOS开发 实现界面跳转翻页等效果
- 常用的GPIO的标准接口函数