二叉树:
669. Trim a Binary Search Tree
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == NULL) return NULL;
if(root->val < low) return trimBST(root->right, low, high);
if(root->val > high) return trimBST(root->left, low , high);
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
108. Convert Sorted Array to Binary Search Tree
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return buildBST(nums, 0, nums.size());
}
TreeNode* buildBST(vector<int>& nums, int left, int right){
//左闭右开区间
if(left >= right) return NULL;
int mid = left + (right-left)/2;
TreeNode* newNode = new TreeNode(nums[mid]);
newNode->left = buildBST(nums, left, mid);
newNode->right = buildBST(nums, mid+1, right);
return newNode;
}
};
确定好区间的开闭
538. Convert BST to Greater Tree
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
if(root == NULL) return NULL;
root->right = convertBST(root->right);
sum += root->val;
root->val = sum;
root->left = convertBST(root->left);
return root;
}
};
Top interview 150(String):
88. Merge Sorted Array
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int p1 = m-1, p2 = n-1;
int i = m+n-1;
while(p1 >= 0 && p2 >= 0){
if(nums1[p1] >= nums2[p2]){
nums1[i] = nums1[p1];
p1--;
}else{
nums1[i] = nums2[p2];
p2--;
}
i--;
}
while(p2>=0){
nums1[i] = nums2[p2];
p2--;
i--;
}
}
};
因为这道题要直接加在nums1里面,所以从后往前
(需不需要resize nums1)
27. Remove Element
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int index = 0;
for(int i=0; i<nums.size(); i++){
if(nums[i] != val){
nums[index] = nums[i];
index++;
}
}
return index;
}
};
26. Remove Duplicates from Sorted Array
1.
lass Solution {
public:
int removeDuplicates(vector<int>& nums) {
int slow = 1, fast = 1;
while(fast < nums.size()){
if(nums[fast] == nums[fast-1]){
fast++;
}else{
nums[slow] = nums[fast];
slow++;
fast++;
}
}
return slow;
}
};
2.
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int slow = 0, fast = 0;
while(fast < nums.size()){
if(nums[fast] != nums[slow]){
slow++;
nums[slow] = nums[fast];
}
fast++;
}
return slow+1;
}
};
要注意如何保留下来第一个数字
80. Remove Duplicates from Sorted Array II
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int dupnum = 0;
int slow = 0, fast = 0;
while(fast < nums.size()){
if(nums[fast] == nums[slow]){
if(slow < fast && dupnum <= 1){
slow++;
nums[slow] = nums[fast];
}
}else{
dupnum = 0;
slow++;
nums[slow] = nums[fast];
}
fast++;
dupnum++;
}
return slow+1;
}
};
出现的一些错误:
1.记录重复次数的当出现>2个的情况时,不需要将dupnum赋值0, 如果赋值0,后面又会重新计数,加进来, 遇到不同的在改为0就可以了文章来源:https://www.toymoban.com/news/detail-663343.html
2.要添加一个slow<fast的情况,不然slow就会跑到fast前面(感觉是考虑到第一个数字,当添加这个条件,就会自动略过第一个数字)文章来源地址https://www.toymoban.com/news/detail-663343.html
到了这里,关于Leetcode 二叉树 669的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!