[leetcode 101] Symmetric Binary Tree

Title: https://leetcode.cn/problems/symmetric-tree/description/

insert image description here

Seeing the topic, I felt that recursion could not be used at first, because the traditional binary tree recursive parameter only has one root, which obviously cannot solve the problem of symmetry. So I think of in-order traversal (left, middle and right), because it is symmetrical, so the result of in-order traversal must be a palindrome sequence, and this is used to judge whether it is symmetric. However, while a symmetric binary tree is necessarily a palindromic sequence, a palindromic sequence is not necessarily a symmetric binary tree. like

insert image description here

Recursion, or recursion, just change the parameter from root to left and right! The two parameters represent two trees, one to the left and one to the right.

class Solution {
    
    
public:
    bool backtracking(TreeNode* leftchild, TreeNode* rightchild) {
    
    
        if (!leftchild && !rightchild) {
    
    
            return true;
        }
        if (!leftchild && rightchild) {
    
    
            return false;
        }
        if (leftchild && !rightchild) {
    
    
            return false;
        }
        if (leftchild->val != rightchild->val) {
    
    
            return false;
        }
        bool left = backtracking(leftchild->left, rightchild->right);
        bool right = backtracking(leftchild->right, rightchild->left);
        return left && right;
    }
    bool isSymmetric(TreeNode* root) {
    
    
        return backtracking(root->left, root->right);

Can it be solved iteratively? OK! Use two queues, one each for left and right

class Solution {
    
    
public:
    bool isSymmetric(TreeNode* root) {
    
    
        queue<TreeNode*> que1, que2;
        TreeNode* p1, *p2;
        if (root->left) {
    
    
            que1.push(root->left);
        }
        if (root->right) {
    
    
            que2.push(root->right);
        }
        while(!que1.empty() && !que2.empty()) {
    
    
            p1 = que1.front();
            p2 = que2.front();
            if (p1->val != p2->val) {
    
    
                return false;
            }
            que1.pop();
            que2.pop();
            if (p1->left && p2->right)  {
    
    
                que1.push(p1->left);
                que2.push(p2->right);
            }
            else if (p1->left || p2->right) {
    
    
                return false;
            }
            if (p1->right && p2->left) {
    
    
                que1.push(p1->right);
                que2.push(p2->left);
            }
            else if (p1->right || p2->left) {
    
    
                return false;
            }
        }
        return que1.empty() && que2.empty();
    }
};

Guess you like

Origin blog.csdn.net/weixin_43742643/article/details/128614418