题解 | #判断是不是平衡二叉树#比官方的代码形式简单

判断是不是平衡二叉树

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

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    bool IsBalanced_Solution(TreeNode* pRoot) {
        // write code here
        int depth = 0;
        return judge(pRoot, depth);
    }
    bool judge(TreeNode* root, int& depth)
    {
        if(root == nullptr)
        {
            depth = 0;
            return true;
        }

        int left = 0;
        int right = 0;
        bool lb = judge(root->left, left);
        bool rb = judge(root->right, right);
        depth = left > right ? left + 1 : right + 1;
        return (left - right <= 1) && (left - right >= -1) && lb && rb;
    }
};

另一个代码

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return bool布尔型
     */
    bool IsBalanced_Solution(TreeNode* pRoot) {
        // write code here
        if(pRoot == nullptr)
            return true;
        int left = deep(pRoot->left);
        int right = deep(pRoot->right);
        if((left - right <= 1) && (left - right >= -1) &&
         IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right))
            return true;
        else
            return false;
    }
  
    int deep(TreeNode* root)
    {
        if(root == nullptr)
            return 0;
        int left = deep(root->left);
        int right = deep(root->right);
        return left > right ? left + 1 : right + 1;
    }
};

全部评论

相关推荐

敢逐云霄志:你打招呼语怎么能这么长,hr都没看下去的欲望,简明扼要说重点,就读于某某学校某某专业,26届应届毕业生,学信网可查,先后在某某公司实习过(如有),然后做过什么项目,想找一份什么样的工作,可实习几个月以上,期待您的回复。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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