두 갈래 나무의 유사성, 거울 문제

1603 단어
두 갈래 트리의 대칭복사:
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)
          return root;
        TreeNode* temp = root->left;
        if(root->right)
          root->left = invertTree(root->right);
        else
          root->left = NULL;
        if(temp)
          root->right = invertTree(temp);
        else
          root->right = NULL;
        return root;
    }
};

100.Same Tree(두 갈래 나무가 동일한지 여부)
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p==NULL&&q!=NULL)
          return false;
        if(p!=NULL&&q==NULL)
          return false;
        if(p==NULL&&q==NULL)
          return true;
          
        if(p->val!=q->val)
          return false;
        else
          return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
    }
};

101. Symmetric Tree
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if(root==NULL)
          return true;
        else
          return isSimilar(root->left,root->right);
    }
    bool isSimilar(TreeNode* p,TreeNode* q)
    {
        if(p==NULL&&q!=NULL)
          return false;
        if(p!=NULL&&q==NULL)
          return false;
        if(p==NULL&&q==NULL)
          return true;
        if(p->val!=q->val)
          return false;
        else
          return isSimilar(p->left,q->right)&&isSimilar(p->right,q->left);
    }
};

좋은 웹페이지 즐겨찾기