题目部分
25.K个一组翻转链表
腾讯的面试题,一个比较简单的hard,但是写了两个小时才oc,要注意细节逻辑
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (k == 1)return head;
ListNode* vh = new ListNode();
vh->next = head;
ListNode* pre = vh;
ListNode* start = head;;
ListNode* end = head;
while (1) {
start = end;
for (int j = 0; j < k; j++) {
if (end != nullptr)
end = end->next;
else
return vh->next;;
}
pair<ListNode*, ListNode*> result = myreverse(start, k);
pre->next = result.first;
pre = result.second;
pre->next = end;
}
return vh->next;
}
pair<ListNode*, ListNode*> myreverse(ListNode* head, int k) {
ListNode* cur1 = head;
ListNode* cur2 = cur1->next;
ListNode* cur3 = cur2->next;
ListNode* rear = head;
for (int i = 1; i < k; i++) {
cur2->next = cur1;
cur1 = cur2;
cur2 = cur3;
rear = cur1;
if (cur3)cur3 = cur3->next;
else {
if (!cur2) {
rear = cur1;
}
else {
cur2->next = cur1;
rear = cur2;
}
return { rear, head };
}
}
return { rear, head };
}
};
669.修剪二叉搜索树
注意不要把满足的子树给丢了就行
class Solution {
public:
TreeNode* traversal(TreeNode*root, int low, int high){
if(root==nullptr)return nullptr;
if(root->val<low){
return traversal(root->right,low,high);
}
if(root->val>high){
return traversal(root->left,low,high);
}
root->left = traversal(root->left,low,high);
root->right = traversal(root->right,low,high);
return root;
}
TreeNode* trimBST(TreeNode* root, int low, int high) {
return traversal(root,low,high);
}
};
108.将有序数组转换为平衡二叉搜索树
自己写的比较冗余,构造了多次数组,不如直接操作下标
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
int size = nums.size();
return traversal(nums,0,size);
}
TreeNode* traversal(vector<int>& nums,int left,int right){
int mid = (left+right)/2;
if(left>=right)return nullptr;
TreeNode* root = new TreeNode(nums[mid]);
root->left = traversal(nums,left,mid);
root->right = traversal(nums,mid+1,right);
return root;
}
};
538.把二叉搜索树转换为累加树
采用逆中序的方法遍历,用pre存值
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
traversal(root);
return root;
}
void traversal(TreeNode* root) {
if (root == nullptr)return;
traversal(root->right);
root->val += pre;
pre = root->val;
traversal(root->left);
return;
}
private:
int pre = 0;
};