My c++ solution, sub-optimal,%>_<%


  • -1
    M
    class Solution {
    public:
        void symmetric(TreeNode *root){
            if(!root) return;
            TreeNode *tmp = root->left;
            root->left = root->right;
            root->right = tmp;
            symmetric(root->left);
            symmetric(root->right);
        }
        
        void inorder(TreeNode *root, vector<int>& res){
            if(!root) return;
            inorder(root->left, res);
            res.push_back(root->val);
            inorder(root->right, res);
        }
        
        void postorder(TreeNode *root, vector<int> &res){
            if(!root) return;
            postorder(root->left,res);
            postorder(root->right,res);
            res.push_back(root->val);
        }
    
        bool isSymmetric(TreeNode* root) {
            if(!root) return true;
            vector<int> inres1, inres2, pores1, pores2;
            inorder(root, inres1);
            postorder(root, pores1);
            symmetric(root);
            inorder(root, inres2);
            postorder(root, pores2);
            
            int i = 0, j = 0;
            for(;i < inres1.size() - 1 && j < inres2.size() - 1; i++, j++){
                if(inres1[i] != inres2[j] || pores1[i] != pores2[j]) return false;
            }
            
            return i == j;
            
        }
    };

  • 0
    S

    You can improve your code by checking the equality of two vectors by
    if(inres1==inres2)
    return 1;


Log in to reply
 

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