236.二叉树的公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left == NULL) return right;
return left;
}
};
200.岛屿数量
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int row = grid.size();
int col = grid[0].size();
if (row == 0) return 0;
int nums_land = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == '1') {
nums_land++;
dfs(grid, i, j);
}
}
}
return nums_land;
}
void dfs(vector<vector<char>>& grid, int i, int j) {
int row = grid.size();
int col = grid[0].size();
grid[i][j] = '0';
if (i - 1 >= 0 && grid[i - 1][j] == '1') dfs(grid, i - 1, j);
if (j - 1 >= 0 && grid[i][j - 1] == '1') dfs(grid, i, j - 1);
if (i + 1 < row && grid[i + 1][j] == '1') dfs(grid, i + 1, j);
if (j + 1 < col && grid[i][j + 1] == '1') dfs(grid, i, j + 1);
}
};
206.反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
144.二叉树前序遍历
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(res, root);
return res;
}
void preorder(vector<int>& res, TreeNode* root) {
if (root == nullptr) return;
res.push_back(root->val);
preorder(res, root->left);
preorder(res, root->right);
}
};
136.只出现一次的数字
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for (auto item : nums) {
res = res ^ item;
}
return res;
}
};