C++ iteration solution using vector in 3ms


  • 0
    V

    using vector is enough.

    bool isSymmetric(TreeNode* root) {
        vector<TreeNode*> v;
        if(root == NULL || (root->left == NULL && root->right == NULL))
            return true;
        else
        {
            if(root->left == NULL && root->right != NULL || root->left != NULL && root->right == NULL || root->left->val != root->right->val)
                return false;
        }
        
        v.push_back(root->left);
        v.push_back(root->right);
        while(v.size() > 0)
        {
            int vLen = v.size(), i;
            for(i = 0; i + 1 < vLen; i = i + 2)
            {
                if(v[i]->val != v[i + 1]->val)
                    return false;
                if(v[i]->left != NULL && v[i + 1]->right != NULL)
                {
                    v.push_back(v[i]->left);
                    v.push_back(v[i + 1]->right);
                }
                else
                {
                    if(v[i]->left != NULL || v[i + 1]->right != NULL)
                        return false;
                }
                if(v[i]->right != NULL && v[i + 1]->left != NULL)
                {
                    v.push_back(v[i]->right);
                    v.push_back(v[i + 1]->left);
                }
                else
                {
                    if(v[i]->right != NULL || v[i + 1]->left != NULL)
                        return false;
                }
            }
            if(i + 1 < vLen)
                return false;
            v.erase(v.begin(), v.begin() + vLen);
        }
        return true;
    }

Log in to reply
 

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