Leikou 101. Symmetric Binary Tree Given a binary tree, check whether it is mirror-symmetrical.

  • Symmetric Binary Tree
    Given a binary tree, check whether it is mirror-symmetrical.
    Lizou original title icon
    The original title portal OvO

  • Iterative implementation
    Use queues for temporary storage of data ( only use queues as data containers, not breadth search~ );
    the conditions for mirror symmetry of the binary tree are:

1. The values ​​of the two nodes currently being compared are the same;
2. The left child of the left node should be equal to the right child of the right node, and the right child of the left node should be equal to the left child of the right node;
accordingly, we use a queue and store each time It is a pair of objects that we need to compare. We need to judge before saving. If the current node is empty, there is no need for subsequent comparison. This cycle ends (directly enters the next cycle condition judgment), if there is one If the node is missing or the values ​​of the two nodes are not equal, then the tree is already asymmetric, and false can be returned; the
code is as follows:

Structure definition:

struct TreeNode {
    
    
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {
    
    }
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {
    
    }
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {
    
    }
  };

Function implementation:

class Solution {
    
    
public:
    bool isSymmetric(TreeNode* root) {
    
    
        queue<TreeNode*> que;
        que.push(root);
        que.push(root);
        while (!que.empty()) {
    
    
            TreeNode* leftNode = que.front();
            que.pop();
            TreeNode* rightNode = que.front();
            que.pop();
            if (!leftNode && !rightNode)
                continue;
                
            if(!leftNode||!rightNode||(leftNode->val!=rightNode->val))
               return false;
               
            que.push(leftNode->left);
            que.push(rightNode->right);

            que.push(leftNode->right);
            que.push(rightNode->left);

        }
        return true;
    }
};

-Recursive deep search
Use pre-order deep search:

class Solution {
    
    
public:
    bool RecurPre(TreeNode* root1, TreeNode* root2) {
    
    
        if(!root1&&!root2)//两个节点都为空
        return true;
        if(!root1||!root2)
        return false;
        return root1->val == root2->val && RecurPre(root1->left, root2->right) && RecurPre(root1->right, root2->left);
    }

    bool isSymmetric(TreeNode* root) {
    
    
        return RecurPre(root, root);
    }
};

Guess you like

Origin blog.csdn.net/Genius_bin/article/details/113338098