662. 二叉树最大宽度
代码实现(看题解)
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
unsigned long long res = 1;
vector<pair<TreeNode *, unsigned long long>> arr;
arr.emplace_back(root, 1L);
while (!arr.empty()) {
vector<pair<TreeNode *, unsigned long long>> tmp;
for (auto &[node, index] : arr) {
if (node->left) {
tmp.emplace_back(node->left, index * 2);
}
if (node->right) {
tmp.emplace_back(node->right, index * 2 + 1);
}
}
res = max(res, arr.back().second - arr[0].second + 1);
arr = move(tmp);
}
return res;
}
};
206. 反转链表
代码实现(部分看题解)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr) {
ListNode* nex = curr->next;
curr->next = prev;
prev = curr;
curr = nex;
}
return prev;
}
};
143. 重排链表
代码实现(自解)
class Solution {
public:
void reorderList(ListNode* head) {
int k = 0;
ListNode* tmp;
while (tmp) {
k++;
tmp = tmp->next;
}
k /= 2;
ListNode* newHead = head;
while (k--) {
ListNode* tail = newHead;
while (tail->next && tail->next->next) {
tail = tail->next;
}
ListNode* tailMinusOne = tail;
tail = tail->next;
tailMinusOne->next = nullptr;
tail->next = newHead->next;
newHead->next = tail;
newHead = tail->next;
}
}
};
25. K 个一组翻转链表
代码实现(自解)
class Solution {
private:
bool check(ListNode* node, vector<int>& tmp, int k) {
int i = 0;
int k1 = k;
while (k1-- && node) {
tmp[i++] = node->val;
node = node->next;
}
return i == k;
}
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head) return nullptr;
vector<int> tmp(k);
ListNode* n1 = head, *n2 = head;
while (check(n1, tmp, k)) {
int k1 = k;
while (k1--) {
n2->val = tmp[k1];
n2 = n2->next;
}
n1 = n2;
}
return head;
}
};