首页 > 学院 > 开发设计 > 正文

109. Convert Sorted List to Binary Search Tree

2019-11-10 17:28:01
字体:
来源:转载
供稿:网友

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);}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表