求二叉树深度、判断是否是平衡二叉树

求二叉树深度:

递归的方法:从根节点按照先序顺序遍历二叉树,返回左子树和右子树中较大的深度,再加上1就是根节点的深度。

C++代码实现:

typedef struct TreeNode{
    int data;
    struct TreeNode* leftchild;
    struct TreeNode* rightchild;

}TreeNode, *Bitree;

int TreeMaxDepth(Bitree pRoot){

    if(pRoot ==  NULL){
        return 0;
    }

    int left = TreeMaxDepth(pRoot->leftchild);
    int right = TreeMaxDepth(pRoot->rightchild);

    return left > right ? left+1 : right+1;

}

二叉树的宽度:

求解二叉树的宽度利用二叉树的层序遍历的思想,把每层的节点保存在队列中,用curwidth记录当前层的宽度,nextwidth记录下一层的宽度。每次把当前层的节点出队,curwidth–,其子节点入队,nextwidth++, 用width来保存最大的宽度。

C++代码如下:

typedef struct TreeNode{
    int data;
    struct TreeNode* leftchild;
    struct TreeNode* rightchild;

}TreeNode, *Bitree;

int WidthOfBiTree(Bitree pRoot){
    if(pRoot == NULL){
        return 0;
    }

    int curWidth = 1;
    int nextWidth = 0;
    int width = 1;
    queue<Bitree> node;

    node.push(pRoot);

    while(!node.empty()){
        while(curWidth!=0){
            Bitree tmp = node.front();
            node.pop();
            if(tmp->leftchild != NULL){
                nextWidth++;
            }
            if(tmp->rightchild != NULL){
                nextWidth++;
            }
            curWidth--;
        }
        if(nextWidth>width){
            width = nextWidth;
        }
        curWidth = nextWidth;
        nextWidth = 0;
    }
    return width;
}

判断是否是平衡二叉树:

平衡二叉树:每个节点的左右子树的深度差不超过1。利用求二叉树深度算法,判断每个节点的左右子树是否满足平衡二叉树的条件即可。

算法一: C++代码实现

bool IsBalance(Bitree pRoot){
    if(pRoot ==  NULL){
        return true;
    }

    int left = TreeMaxDepth(pRoot->leftchild);
    int right = TreeMaxDepth(pRoot->rightchild);

    int diff = left - right;
    if(diff < -1 || diff > 1){
        return false;
    }

    return IsBalance(pRoot->leftchild) && IsBalance(pRoot->rightchild);
}

但是上诉算法不够高效,会重复遍历遍历节点。根据二叉树的后序遍历的思想,我们可以设计出更高效的算法,每遍历到一个节点就记录下当前节点的深度,这样就不需要重复遍历了,只需要线性时间即可判断左右子树的深度是否满足平衡二叉树的条件。

算法二:C++代码实现:

bool IsBalance_fast(Bitree pRoot, int& pDepth){
    if(pRoot == NULL){
        pDepth = 0;
        return true;
    }

    int left, right;
    if(IsBalance_fast(pRoot->leftchild, left) && IsBalance_fast(pRoot->rightchild, right)){
        int diff = left - right;
        if(diff >= -1 && diff <=1){
            pDepth = left > right ? left + 1 : right + 1;
            return true;
        }
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值