23. 合并 K 个升序链表 - 力扣(LeetCode)
若lists有k个元素,调用k - 1次(两个有序链表的合并)即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* _mergeKLists(ListNode *l1, ListNode *l2)
{
ListNode *head = new ListNode;
ListNode *del = head;
while (l1 && l2)
{
if (l1->val < l2->val) head->next = l1, l1 = l1->next;
else head->next = l2, l2 = l2->next;
head = head->next;
}
if (l1) head->next = l1;
else head->next = l2;
ListNode *res = del->next;
delete del;
return res;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 0) return nullptr;
ListNode *ans = lists[0];
for (int i = 1; i < lists.size(); ++ i)
{
ans = _mergeKLists(ans, lists[i]);
}
return ans;
}
};
94. 二叉树的中序遍历 - 力扣(LeetCode)
使用栈模拟递归调用的过程
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode *> st;
vector<int> ans;
while (root || st.size())
{
while (root)
{
st.push(root);
root = root->left;
}
root = st.top(); st.pop();
ans.push_back(root->val);
root = root->right;
}
return ans;
}
};