跳转至

101.对称二叉树 (Easy)*

题目描述*

给定一个二叉树,检查它是否是镜像对称的。

示例*

二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:*

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

代码*

递归和迭代 dfs,或 bfs。

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root == nullptr) {
            return true;
        }
        return helper(root->left, root->right);
    }
    bool helper(TreeNode *left, TreeNode *right) {
        if(left == nullptr && right != nullptr || left != nullptr && right == nullptr) {
            return false;
        }
        if(left != nullptr && right != nullptr) {
            if(left->val != right->val) {
                return false;
            }
            return helper(left->left, right->right) && helper(left->right, right->left);
        }
        return true;
    }
};
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root == nullptr) {
            return true;
        }
        stack<TreeNode*> leftStack;
        stack<TreeNode*> rightStack;
        TreeNode *curLeft = root->left;
        TreeNode *curRight = root->right;
        while(curLeft != nullptr || !leftStack.empty() || curRight != nullptr || !rightStack.empty()) {
            while(curLeft != nullptr) {
                leftStack.push(curLeft);
                curLeft = curLeft->left;
            }
            while(curRight != nullptr) {
                rightStack.push(curRight);
                curRight = curRight->right;
            }
            if(leftStack.size() != rightStack.size()) {
                return false;
            }
            curLeft = leftStack.top();
            leftStack.pop();
            curRight = rightStack.top();
            rightStack.pop();
            if(curRight->val != curLeft->val) {
                return false;
            }
            curLeft = curLeft->right;
            curRight = curRight->left;
        }
        return true;
    }
};
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root == nullptr) {
            return true;
        }
        queue<TreeNode*> helpQueue;
        helpQueue.push(root);
        helpQueue.push(root);
        while(!helpQueue.empty()) {
            TreeNode *cur1 = helpQueue.front();
            helpQueue.pop();
            TreeNode *cur2 = helpQueue.front();
            helpQueue.pop();
            if(cur1 == nullptr && cur2 == nullptr) {
                continue;
            }
            if(cur1 == nullptr || cur2 == nullptr) {
                return false;
            }
            if(cur1->val != cur2->val) {
                return false;
            }else {
                helpQueue.push(cur1->left);
                helpQueue.push(cur2->right);
                helpQueue.push(cur1->right);
                helpQueue.push(cur2->left);
            }
        }
        return true;
    }
};

最后更新: July 23, 2022