C++ solution


  • 0
    A
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSameTree(TreeNode* p, TreeNode* q) {
            queue <TreeNode *> pQ, qQ;
            
            pQ.push(p);
            qQ.push(q);
            
            while(!pQ.empty() && !qQ.empty())
            {
                TreeNode *tempP = pQ.front();
                pQ.pop();
                TreeNode *tempQ = qQ.front();
                qQ.pop();
                
                if((tempP != NULL) && (tempQ != NULL))
                {
                    if (tempP->val!=tempQ->val)
                        return false;
                    else
                    {
                        pQ.push(tempP->left);
                        pQ.push(tempP->right);
                        qQ.push(tempQ->left);
                        qQ.push(tempQ->right);
                    }
                }
                else if ((tempP != NULL) || (tempQ != NULL))
                    return false;
            }
            if(!pQ.empty() || !qQ.empty())
                return false;
            return true;
            
        }
    };
    

Log in to reply
 

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