LeetCode Convert Sorted List to Binary Search Tree
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { ListNode *cur = head; int len = 0; while (cur != NULL) { len++; cur = cur->next; } return dfs(head, len); } TreeNode* dfs(ListNode *head, int len) { if (head == NULL || len <= 0) return NULL; int mid = len / 2; ListNode* cur = head; while (mid > 0) { cur = cur->next; mid--; } TreeNode* nroot = new TreeNode(cur->val); nroot->left = dfs(head, len / 2); nroot->right= dfs(cur->next, (len - 1) / 2); return nroot; } };
要改进
第二轮:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
使用build函数产生一个树形调用结构(中序遍历),使用了一个类成员变量,表示当前使用的节点,因为我们知道中序遍历所获得的节点顺序就是所有节点排序后的顺序即sorted list中的序列。这样一来可以省去通过循环遍历获取当前片段中点元素。复杂度从O(nlogn)降低到O(n)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // 8:37 class Solution { private: ListNode* cur; public: TreeNode *sortedListToBST(ListNode *head) { int cnt = 0; cur = head; while(head != NULL) { cnt++; head = head->next; } return build(0, cnt); } TreeNode* build(int start, int end) { if (start >= end) { return NULL; } int mid = (start + end) / 2; TreeNode* leftChild = build(start, mid); TreeNode* parent = new TreeNode(cur->val); parent->left = leftChild; cur = cur->next; TreeNode* rightChild = build(mid+1, end); parent->right = rightChild; return parent; } };