8.22刷题笔记

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值