Short iterative solution using a stack of pairs

  • 0

    My following solution uses a stack of pairs for easy to understand.

    bool isSymmetricIterative(TreeNode *root) {
        if (!root)
            return true;
        stack<pair<TreeNode *, TreeNode *>> traversal_stack;
        traversal_stack.emplace(root->left, root->right);
        while (!traversal_stack.empty()) {
            auto cur =;
            TreeNode *left_root = cur.first, *right_root = cur.second;
            if (!left_root && !right_root)
                return true;
            if (!left_root || !right_root)
                return false;
            if (left_root->val != right_root->val)
                return false;
            traversal_stack.emplace(left_root->left, right_root->right);
            traversal_stack.emplace(left_root->right, right_root->left);
        return true;

Log in to reply

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