题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */
#include "math.h"

//返回当前树的深度
#include <stdbool.h>
#include <stdlib.h>
int depth_tree(struct TreeNode* node)
{
    if(node==NULL)
        return 0;
    int depth1=depth_tree(node->left);
    int depth2=depth_tree(node->right);
    //这里有一点抽象,可以画个简单的图理解一下,初值为0,但是对于没有子结点的结点来说:depth1与depth2都等于0,所以返回1,以此类推
    int depth = depth1>depth2? depth1+1:depth2+1;
    return depth;
}

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pRoot TreeNode类 
 * @return bool布尔型
 */
bool IsBalanced_Solution(struct TreeNode* pRoot ) {
    // write code here
    if(pRoot==NULL)
        return true;
    int L=depth_tree(pRoot->left);
    int R=depth_tree(pRoot->right);
    if(abs(L-R)>1)
        return false;
    return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}

全部评论

相关推荐

那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
完美的潜伏者许愿简历...:隐藏信息被你提取出来了,暗示,这就是暗示
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务