二叉树的相关题型

目录

前言

翻转二叉树

相同二叉树

对称二叉树

二叉树的另一颗子树

平衡二叉树


前言

    作为笔记存放着,忘记了的话会拿出来看看。

翻转二叉树

    翻转二叉树就是把原二叉树镜像对称,采用递归算法

struct TreeNode* invertTree(struct TreeNode* root){
    if(root==NULL)
        return NULL;
    struct TreeNode* tem=NULL;
    tem=root->left;
    root->left=root->right;
    root->right=tem;
    invertTree(root->left);
    invertTree(root->right);
    return root;
}

相同二叉树

    判断两颗树是否相同

bool isSameTree(struct TreeNode* p, struct TreeNode* q){
    if(q==NULL && p==NULL)
        return true;
    else if(q==NULL || p==NULL)
        return false;
    else if(q->val != p->val)
        return false;
    else 
        return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    
}

对称二叉树

    和上面镜像的二叉树很想,但是该题是判断两棵树是否镜像对称

bool compare(struct TreeNode* left,struct TreeNode* right){
    if(left==NULL && right==NULL)
        return true;
    else if(left==NULL || right==NULL)
        return false;
    else if(left->val != right->val)
        return false;
    return compare(left->left,right->right) && compare(left->right,right->left);
}

bool isSymmetric(struct TreeNode* root){
    if(root==NULL)
        return true;
    return compare(root->left,root->right);
}

二叉树的另一颗子树

    判断subRoot是否是root的一部分

bool issame(struct TreeNode* q,struct TreeNode* p){
    if(q==NULL && p==NULL)
        return true;
    else if(q==NULL || p==NULL)
        return false;
    else if(q->val != p->val)
        return false;
    else 
        return issame(p->left,q->left) && issame(p->right,q->right);
}

bool isSubtree(struct TreeNode* root, struct TreeNode* subRoot){
    if(root==NULL )
        return false;
    
    return issame(root,subRoot) || isSubtree(root->left,subRoot) || isSubtree(root->right,subRoot);
}

平衡二叉树

    平衡二叉树的定义为:一个二叉树每个节点左右两个子树的高度差的绝对值不超过1

int calculate(struct TreeNode* root){
    if(root==NULL)
        return 0;
    return 1+fmax(calculate(root->left),calculate(root->right));
}

bool isBalanced(struct TreeNode* root){
    if(root==NULL)
        return true;
    if(((calculate(root->left)-calculate(root->right)>=-1) && (calculate(root->left)-calculate(root->right)<=1)) && isBalanced(root->left) && isBalanced(root->right))
        return true;
    return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值