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

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

109. Convert Sorted List to Binary Search Tree

2019-11-09 19:44:44
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(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);}

方法二,模擬樹(shù)的中序遍歷,自底向上建樹(shù),注意這里指向指針的指針

C語(yǔ)言

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ā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 古田县| 广德县| 寿阳县| 东港市| 甘泉县| 泰安市| 隆昌县| 府谷县| 新龙县| 武山县| 黑河市| 尉犁县| 乌恰县| 建昌县| 凤凰县| 云梦县| 屯昌县| 四川省| 江阴市| 疏勒县| 灯塔市| 乌海市| 贵阳市| 习水县| 宁晋县| 攀枝花市| 尖扎县| 九江县| 抚顺县| 永川市| 开封市| 大荔县| 台前县| 易门县| 聊城市| 台湾省| 门头沟区| 丹东市| 凭祥市| 常宁市| 平果县|