国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

109. Convert Sorted List to Binary Search Tree

2019-11-09 19:23:04
字體:
供稿:網(wǎng)友

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

法一

思想同數(shù)組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);}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 萍乡市| 墨脱县| 河南省| 久治县| 拜城县| 兴文县| 多伦县| 晴隆县| 溧水县| 增城市| 遂溪县| 奇台县| 县级市| 叶城县| 嵊泗县| 台南县| 东莞市| 建水县| 荆州市| 敖汉旗| 乌鲁木齐县| 延寿县| 宁海县| 金塔县| 洪洞县| 景德镇市| 大姚县| 雷山县| 会昌县| 巴青县| 鄢陵县| 淮北市| 比如县| 含山县| 皮山县| 时尚| 沂南县| 九龙县| 萍乡市| 巨野县| 涿州市|