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

2021-09-18 15:24:28 浏览数 (1)

1 分治法-递归

代码语言:javascript复制
/**
 * 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

代码语言:javascript复制
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);
    }
};

0 人点赞