(C++) same tree + invert tree


  • 1
    M

    This problem in fact is asking whether root->left and the inverted root->right are the same tree. Hence the solution:

    class Solution {

    public:

    TreeNode* invertTree(TreeNode* root) {
        if (root == 0) {
            return NULL; 
        }
        
        TreeNode *holder = root->left; 
        root->left = invertTree(root->right); 
        root->right = invertTree(holder); 
        
        return root;
    }
    
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == 0 and q == 0) {
            return true;
        }
        else if (p == 0 and q!= 0) {
            return false;
        }
        else if (p != 0 and q == 0) {
            return false;
        }
        else if (p->val != q->val) {
            return false; 
        }
        else {
            return (isSameTree(p->left, q->left) and isSameTree(p->right, q->right));
        }
    }
    
    bool isSymmetric(TreeNode* root) {
        if (root == 0) {
            return true;
        }
        else {
            return isSameTree(root->left, invertTree(root->right));
        }
    }
    

    };


Log in to reply
 

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