自学内容网 自学内容网

LeetCode Hot100 | Day3 | 二叉树:翻转二叉树&&对称二叉树

LeetCode Hot100 | Day3 | 二叉树:翻转二叉树&&对称二叉树

226.翻转二叉树

226. 翻转二叉树 - 力扣(LeetCode)

后序遍历交换两个结点就行

完整代码:

class Solution {
public:
    void tra(TreeNode *t)
    {
        if(t==nullptr)
            return;
        tra(t->left);
        tra(t->right);
        swap(t->left,t->right);
    }
    TreeNode* invertTree(TreeNode* root) {
        tra(root);
        return root;
    }
};

101.对称二叉树

101. 对称二叉树 - 力扣(LeetCode)

层序遍历来做

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        queue<TreeNode *> q;
        if(root==nullptr)
            return true;
        q.push(root->left);
        q.push(root->right);
        while(!q.empty())
        {
            TreeNode *t1=q.front();
            q.pop();
            TreeNode *t2=q.front();
            q.pop();
            if(t1==nullptr&&t2==nullptr)
                continue;
            else if(t1==nullptr&&t2!=nullptr)
                return false;
            else if(t1!=nullptr&&t2==nullptr)
                return false;
            else if(t1!=nullptr&&t2!=nullptr)
                if(t1->val!=t2->val)
                    return false;
            else 
                q.push(t1->left);
                q.push(t2->right);
                q.push(t1->right);
                q.push(t2->left);
        }
        return true;
    }
};

递归法:

class Solution {
public:
    bool is(TreeNode *l,TreeNode *r)
    {
        if(l==nullptr&&r==nullptr)
            return true;
        else if(l!=nullptr&&r==nullptr)
            return false;
        else if(l==nullptr&&r!=nullptr)
            return false;
        else if(l->val!=r->val)
            return false;
        bool left=is(l->left,r->right);
        bool right=is(l->right,r->left);
        return left&&right;
    }
    bool isSymmetric(TreeNode* root) {
        if(root==nullptr)
            return true;
        return is(root->left,root->right);
    }
};

(代码随想录DAY16)


原文地址:https://blog.csdn.net/m0_74795952/article/details/142788228

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!