Leetcode|二叉树的属性|101. 对称二叉树

在这里插入图片描述

1 分治法-递归

/**
 * Definition for a binary tree node.
 * 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) {}
 * };
 */
class Solution {
    
    
public:
    bool recursive(TreeNode* left, TreeNode* right) {
    
    
        if (!left && !right) return true;
        if (!left || !right) return false;
        if (left->val == right->val)
            return recursive(left->left, right->right) && recursive(left->right, right->left);
        return false;
    }
    bool isSymmetric(TreeNode* root) {
    
    
        if (!root) return true;
        return recursive(root->left, root->right);
    }
};

在这里插入图片描述

2 迭代法-BFS

class Solution {
    
    
public:
    bool bfs(TreeNode* left, TreeNode* right) {
    
    
        if (!left) return true;
        queue<TreeNode*> q;
        q.push(left); 
        q.push(right);
        while (!q.empty()) {
    
    
            int sz = q.size();
            TreeNode* left_ptr = q.front(); q.pop();
            TreeNode* right_ptr = q.front(); q.pop();
            if (!left_ptr && !right_ptr) continue;
            if (!left_ptr || !right_ptr) return false;
            if (left_ptr->val != right_ptr->val) return false;
            q.push(left_ptr->left);
            q.push(right_ptr->right);

            q.push(right_ptr->left);
            q.push(left_ptr->right); 
        }
        return true;
    }
    bool isSymmetric(TreeNode* root) {
    
    
        return bfs(root, root);
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/SL_World/article/details/114307427