Level traversal Solution


  • 0
    S
    class Solution {
    public:
        bool isSymmetric(TreeNode* root) {
            
            if(root==nullptr)
                return true;
            vector<TreeNode*> levelVec;
            vector<int> valVec;
            levelVec.push_back(root);
            valVec.push_back(root->val);
            while(!levelVec.empty()) {
                int size = valVec.size();
                for(int  j = 0;j<size/2;++j) {
                    if((valVec[j])!=(valVec[size-j-1]))return false;
                }
                valVec.clear();
                size = levelVec.size();
                for(int i = 0;i!=size;++i) {
                    auto bac = *(levelVec.end()-1);
                    if(bac->left){
                        levelVec.insert(levelVec.begin(),bac->left);
                        valVec.insert(valVec.begin(),bac->left->val);
                    }else {
                        valVec.insert(valVec.begin(),-1);
                    }
                    if(bac->right){
                        levelVec.insert(levelVec.begin(),bac->right);
                        valVec.insert(valVec.begin(),bac->right->val);
                    }else {
                        valVec.insert(valVec.begin(),-1);
                    }
                    levelVec.pop_back();   
                    
                    
                }
            }
            return true;
        }
    };
    

Log in to reply
 

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