zoukankan      html  css  js  c++  java
  • [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.

    Example 1:

    Given the following tree [3,9,20,null,null,15,7]:

        3
       / 
      9  20
        /  
       15   7

    Return true.

    Example 2:

    Given the following tree [1,2,2,3,3,null,null,4,4]:

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    Return false.

    题目要求判断给定的二叉树是不是平衡二叉树。平衡二叉树要求每个结点的左右子树层数相差不超过1层。

    因为每个结点的都要符合平衡二叉树的要求,因此使用递归的方法进行求解。

    方法一:可以计算每个结点的左右子树的层数来判断是否为平衡二叉树。

    代码:

    class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            if(!root || (!root->left && !root->right))return true;
            
            if(abs(layer(root->left)-layer(root->right))>1)return false;
            return isBalanced(root->left) && isBalanced(root->right);
        }
        int layer(TreeNode* root){
            if(!root)return 0;
            return max(1+layer(root->left),1+layer(root->right));
        }
    };

    方法二:当子树为非平衡二叉树时就可以不再进行层数的计算和比较了,直接得出二叉树不平衡的结果。

    class Solution {
    public:
        bool isBalanced(TreeNode* root) {
            if(layer(root)==-1)return false;
            else return true;
        }
        int layer(TreeNode* root){
            if(!root)return 0;
            int left,right;
            left=layer(root->left);
            right=layer(root->right);
            if(left==-1 || right==-1)return -1;
            if(abs(left-right)>1)return -1;
            return 1+max(left,right);
        }
    };

    这里需要注意,不要过多的重复递归,否则当二叉树较大时容易导致运行时间过长。

  • 相关阅读:
    LUSE: 无监督数据预训练短文本编码模型
    LM-MLC 一种基于完型填空的多标签分类算法
    一种基于均值不等式的Listwise损失函数
    知识蒸馏基本知识及其实现库介绍
    自然语言处理中的负样本挖掘
    milvus和faiss安装及其使用教程
    Pyinstaller打包通用流程
    自我介绍
    作业十二
    作业十一
  • 原文地址:https://www.cnblogs.com/cff2121/p/10974514.html
Copyright © 2011-2022 走看看