C++ short iterative sln 16ms


  • 0
    L

    class Solution {
    public:
    bool isSymmetric(TreeNode *root) {
    if(root == nullptr) return true;
    return isSymTree(root->left, root->right);
    }

    bool isSymTree(TreeNode *p, TreeNode *q) {
        vector<pair<TreeNode*, TreeNode*>> stack = {{p, q}};
        while(!stack.empty()) {
            auto const nodes = stack.back();
            stack.pop_back();
            if(nodes.first == nullptr || nodes.second == nullptr) {
                if(nodes.first != nodes.second)
                    return false;
            } else {
                if(nodes.first->val != nodes.second->val)
                    return false;
                stack.emplace_back(nodes.first->right, nodes.second->left);
                stack.emplace_back(nodes.first->left, nodes.second->right);
            }
        }
        return true;
    }
    

    };


Log in to reply
 

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