美文网首页
二叉树的相似、镜像问题

二叉树的相似、镜像问题

作者: juexin | 来源:发表于2017-04-13 16:36 被阅读0次

    二叉树的镜像:

    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);
        }
    };
    

    相关文章

      网友评论

          本文标题:二叉树的相似、镜像问题

          本文链接:https://www.haomeiwen.com/subject/gsxvittx.html