classSolution(object): defmergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ self.nodes = [] head = point = ListNode(0) for l in lists: while l: self.nodes.append(l.val) l = l.next for x in sorted(self.nodes): point.next = ListNode(x) point = point.next return head.next
Time complexity: $O(kN) where $N$ is the total number of nodes in the final returned linked-list.
Space complexity: $O(N)$ creating a new linked-list with $N$ nodes.
Approach 2: Optimize Approach 1 by Priority Queue
Almost the same as the one above but optimize the comparison process by priority queue. This approach can not only reduce the time complexity, but also significantly simplify the codes.
structNode_t { Node_t(ListNode* _node, int _val): node(_node), val(_val) {} booloperator > (const Node_t& cmp) const { return val > cmp.val; } ListNode *node; int val; };
classSolution { public: ListNode* mergeKLists(vector<ListNode*>& lists){ priority_queue<Node_t, vector<Node_t>, greater<Node_t>> que; ListNode *head = new ListNode(0); ListNode *point = head; for (ListNode *ptr : lists) { if (ptr != NULL) que.push(Node_t(ptr, ptr->val)); } while (!que.empty()) { Node_t tmp = que.top(); que.pop(); point->next = new ListNode(tmp.val); point = point->next; if (tmp.node->next != NULL) { que.push(Node_t(tmp.node->next, tmp.node->next->val)); } } point = head->next; delete head; return point; } };
Time complexity: C++中的priority_queue底层是由大顶堆/小顶堆实现的,因此每次插入队列的复杂度为$O(\log(k))$,yielding a total time complexity of $O(N\log(k))$
Space complexity: $O(N+k)$, where $O(N)$ for the new returned linked-list, and $O(k)$ for the priority_queue. In most cases, when $k$ is far less than $N$, the space complexity is $O(N)$.
classSolution { public: intgetMinimumDifference(TreeNode* root){ if (root == NULL) return0; return midOrder(root); } intmidOrder(TreeNode *root){ stack<TreeNode*> st; TreeNode *p = root; int cur = 1000000, last = -1000000, ans = 10000000; while (p != NULL || !st.empty()) { while (p != NULL) { st.push(p); p = p->left; } if (!st.empty()) { p = st.top(); st.pop(); cur = p->val; if (cur - last < ans) ans = cur - last; last = p->val; p = p->right; } } return ans; } };
222. Count Complete Tree Nodes
Given a complete binary tree, count the number of nodes.
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.