Not the most optimal, yet very easy to understand c++ 8ms solution.


  • 0
    S

    Simple brute force idea:

    Traverse the left subtree in ROOT-RIGHT-LEFT fashion. Meanwhile store it in a vector.

    Traverse the right subtree in ROOT-LEFT-RIGHT fashion. Meanwhile store it in a vector.

    Compare the two vectors for equality.

    class Solution {
       public:
    
    void preorder(TreeNode *root,vector<int> &v){
        if(root==NULL)
        {
            v.push_back(NULL);
            return;
        }
        v.push_back(root->val);
        preorder(root->left,v);
        preorder(root->right,v);        
    }
    void myorder(TreeNode *root,vector<int> &v){
        if(root==NULL)
        {
            v.push_back(NULL);
            return;
        }
            
        v.push_back(root->val);
        myorder(root->right,v);
        myorder(root->left,v);
     
    }
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)
            return 1;
        vector<int> vec;
        vector<int> v;
        
        myorder(root->left,v);
        preorder(root->right,vec);
        if(v.size()!=vec.size())
            return 0;
        if(v!=vec)
            return 0;
        return 1; 
    }
    

    };


Log in to reply
 

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