【关关的刷题日记64】Leetcode 110 Balanced Binary Tree

时间:2022-05-08
本文章向大家介绍【关关的刷题日记64】Leetcode 110 Balanced Binary Tree,主要内容包括题目、思路、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关关的刷题日记64 – Leetcode 110 Balanced Binary Tree

题目

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

题目的意思是给定一个二叉树,判断它是否是平衡树。平衡树的任何一个节点的左右子树的深度差不超过1。

思路

思路:可见判断一棵树是否是平衡树,需要满足两个条件:1、该树的左右子树都是平衡树 2、该树的左右子树的深度差不超过1。判断该树的左右子树是否是平衡树的过程和判断这棵树是否是平衡树的过程一样,采用递归的思路。

class Solution {public:
    int depth(TreeNode* root)
    {
        if (root==nullptr)
            return 0;
        int count=0,left=1,right=1;
        left+=depth(root->left);
        right+=depth(root->right);
        return max(left, right);
    }

    bool isBalanced(TreeNode* root) {
        if(!root)
            return true;
        int l=depth(root->left), r=depth(root->right);
        return (l==r || l==r+1 || l==r-1) && isBalanced(root->left) && isBalanced(root->right); 
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。