Cpp BFS manner iterative


  • 0
    C
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            if (root == NULL) return true;
            queue<TreeNode *> q;
            if (root->left == NULL && root->right == NULL) {
                return true;
            }
            
            if (root->left != NULL) {
                q.push(root->left);
            }
            if (root->right != NULL) {
                q.push(root->right);
            }
            while (!q.empty()) {
                if (q.size() % 2 != 0) {
                    return false;
                }
                TreeNode *left = q.front();
                q.pop();
                TreeNode *right = q.front();
                q.pop();
                
                if (left->val != right-> val) {
                    return false;
                }
                
                if (left->left != NULL) {
                    q.push(left->left);
                }
                if (right->right != NULL) {
                    q.push(right->right);
                }
                if (q.size() % 2 != 0) return false;
                if (left->right != NULL) {
                    q.push(left->right);
                }
                if (right->left != NULL) {
                    q.push(right->left);
                }
            }
            return true;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.