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

首頁 > 學院 > 開發設計 > 正文

109. Convert Sorted List to Binary Search Tree

2019-11-09 19:15:23
字體:
來源:轉載
供稿:網友

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);}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 延长县| 赤城县| 阳城县| 万源市| 永昌县| 万荣县| 礼泉县| 广平县| 冀州市| 长顺县| 洛浦县| 余姚市| 景谷| 永昌县| 怀化市| 焦作市| 东阳市| 商城县| 镇赉县| 庄浪县| 九江县| 疏勒县| 台州市| 壤塘县| 阿拉善右旗| 河源市| 南靖县| 商城县| 青川县| 舟曲县| 吉木萨尔县| 宁城县| 永靖县| 株洲市| 松滋市| 积石山| 元江| 平度市| 田阳县| 东山县| 福安市|