My non-recursive C++ code ran out of memory. Why?


  • 0
    V
    class Solution {
        public:
            bool isSameTree(TreeNode *p, TreeNode *q) {
                queue<TreeNode *> t1, t2;
                if (p == NULL && q == NULL)
                    return true;
                if (p == NULL || q == NULL)
                    return false;
                t1.push(p);
                t2.push(q);
                while (!t1.empty() && !t2.empty()) {
                    int n1 = t1.size(), n2 = t2.size();
                    if (n1 != n2) {
                        return false;
                    }
                    TreeNode *node1 = t1.front(), *node2 = t2.front();
                    t1.pop();
                    t2.pop();
                    for (int i = 0; i < n1; i++) {
                        if (node1->val != node2->val) {
                            return false;
                        }
                        if (node1->left != NULL)
                            t1.push(node1->left);
                        if (node1->right != NULL)
                            t1.push(node1->right);
                        if (node2->left != NULL)
                            t2.push(node2->left);
                        if (node2->right != NULL)
                            t2.push(node2->right);
                    }
                }
                return true;
            }
        };
    

    I don't know why, I haven't write any dangerous code. Is the test data too big?


Log in to reply
 

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