2022/2/22 剑指OFFER 练习

剑指 Offer 27. 二叉树的镜像

1.方法:后序遍历来交换左右子树
2.代码

class Solution {
public:
     TreeNode* mirrorTree(TreeNode* root) {
         if(root==NULL)
            return root;
         TreeNode* tmpl=mirrorTree(root->left);
         TreeNode* tmpr=mirrorTree(root->right);
         root->left=tmpr;
         root->right=tmpl;
         return root;
    }
};

剑指 Offer 28. 对称的二叉树

1.方法
(1)第一种(自己想的):先做出镜像二叉树,再将镜像二叉树和原本的二叉树比较看是不是一样的。需要两次递归。
(2)第二种(学习别人,效率更高):依据规律,从根节点开始,左子树和右子树比较,再到左子树的左子树和右子树的右子树、左子树的右子树和右子树的左子树……如此递归下去。需要一次递归。
2.代码
(1)第一种

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root){
        if(root==NULL) return NULL;
        TreeNode* tmpl=mirrorTree(root->left);
        TreeNode* tmpr=mirrorTree(root->right);
        TreeNode* mroot=(TreeNode*)malloc(sizeof(TreeNode));
        mroot->val=root->val;
        mroot->left=tmpr;
        mroot->right=tmpl;
        return mroot;
    }
    bool Judge(TreeNode *root,TreeNode *mroot){
        //根、左、右
        if(root==NULL&&mroot==NULL) return true;
        if(root==NULL||mroot==NULL) return false;
        if(root->val!=mroot->val) return false;
        return Judge(root->left,mroot->left)&&Judge(root->right,mroot->right);
    }
    bool isSymmetric(TreeNode* root) {
        //先镜像,再判断
        TreeNode *mroot=mirrorTree(root);
        bool flag=Judge(root,mroot);
        return flag;
    }
};

(2)第二种

class Solution {
public:
    bool Judge(TreeNode* leftTree,TreeNode* rightTree){
        if(leftTree==NULL&&rightTree==NULL) return true;
        if(leftTree==NULL||rightTree==NULL||rightTree->val!=leftTree->val) return false;
        return Judge(leftTree->right,rightTree->left)&&Judge(leftTree->left,rightTree->right);
    }
    bool isSymmetric(TreeNode* root) {
        if(root==NULL) return true;
        else return Judge(root->left,root->right);
    }
};

3.心得:需要掌握如何比较两颗二叉树是否相同,注意对于return这样return Judge(leftTree->right,rightTree->left)&&Judge(leftTree->left,rightTree->right);的应用!!不要被绕晕!

剑指 Offer 10- I. 斐波那契数列

1.方法
(1)递归:会TLE
(2)for循环,用pre1和pre2来记录并保持更新
(3)直接算出从1到n的斐波那契数列并保存到数组中,最后直接查数组即可
注:不要忘记最后的取模!!!
2.代码
(1)第二种方法

class Solution {
public:
    int fib(int n) {
        if(n==0) return 0;
        if(n==1||n==2) return 1;
        int pre1=1,pre2=1,now;
        for(int i=3;i<=n;i++){
            now=(pre1+pre2)%1000000007;
            pre1=pre2;
            pre2=now;
        }
        return now;
    }
};

(2)第三种方法

class Solution {
public:
    int fib(int n) {
        if(n==0) return 0;
        if(n==1||n==2) return 1;
        vector<int> fl(n+1);
        fl[0]=0;
        fl[1]=1;
        fl[2]=1;
        for(int i=3;i<=n;i++)
            fl[i]=(fl[i-1]+fl[i-2])%1000000007;
        return fl[n];
    }
};

你可能感兴趣的:(剑指offer,算法,数据结构,leetcode)