国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 白银市| 兴宁市| 东阿县| 棋牌| 黔西县| 南涧| 钦州市| 廉江市| 华容县| 宁乡县| 武川县| 临泉县| 康乐县| 石林| 长治市| 南雄市| 黔西县| 南部县| 六枝特区| 二连浩特市| 凤庆县| 北碚区| 灵寿县| 鄂伦春自治旗| 顺义区| 涿鹿县| 泰顺县| 忻城县| 定兴县| 邳州市| 化隆| 仙游县| 资源县| 比如县| 开封县| 涿州市| 徐闻县| 海原县| 波密县| 如东县| 孝义市|