Sword refers to offer acwing 39 symmetrical binary tree

Topic

Insert picture description here

answer

For a symmetric binary tree, except for the root node, all subtrees are symmetrical, that is, the left son of the left subtree is equal to the right son of the right subtree, and the right son of the left subtree is equal to the left son of the right subtree. Direct recursive dfs judgment can be

Code

/**
 * 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:
    bool dfs(TreeNode *p, TreeNode *q) {
    
    
        if (!p || !q) return !p && !q;
        if (p->val != q->val) return false;
        return dfs(p->left, q->right) && dfs(p->right, q->left);
    }
    
    bool isSymmetric(TreeNode *root) {
    
    
        if (!root) return true;
        return dfs(root->left, root->right);
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115040962