Title:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Title:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:自顶向下
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* sortedListToBST(ListNode* head) { return maker(head,getLength(head)); } TreeNode* maker(ListNode* head, int len){ if (len == 0) return NULL; if (len == 1) return new TreeNode(head->val); ListNode* cur = getN(head,len/2); TreeNode* root = new TreeNode(cur->val); root->left = maker(head,len/2); root->right = maker(cur->next,len-len/2-1); } ListNode* getN(ListNode*p, int n){ ListNode* l = p; int count = 0; while (count++ < n){ l = l->next; } return l; } int getLength(ListNode* p){ ListNode * l = p; int len = 0; while (l){ len++; l = l->next; } return len; } };
自底向上
class Solution { public: TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode *p = head; while (p) { len++; p = p->next; } return sortedListToBST(head, 0, len - 1); } private: TreeNode* sortedListToBST(ListNode*& list, int start, int end) { if (start > end) return nullptr; int mid = start + (end - start) / 2; TreeNode *leftChild = sortedListToBST(list, start, mid - 1); TreeNode *parent = new TreeNode(list->val); parent->left = leftChild; list = list->next; parent->right = sortedListToBST(list, mid + 1, end); return parent; } };
时间: 2024-10-07 16:03:17