• [Leetcode] 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,想到用层次遍历,找到第一个没有左右孩子的结点所在的层,然后继续遍历,只要层差超过1就返回false,结果被打脸。例 {1,#,2,#,3}不是平衡二叉树,但就我最初的想法是符合,所以思路不对 。后来又想到,左、右孩子中只要有一个为NULL就为最小层,然后和整个层数去比,结果又无情的被打脸。例:{1,2,2,3,3,3,3,4,4,4,4,4,4,#,#,5,5},其次我对最小层的理解也是不对的。究其所有,是没有理解平衡二叉树的概念。是任意结点的两子树的深度不超过1

    特别值得注意的是,一棵子树的深度指的是最大深度,两棵子树的深度差应为两者的最大深度之差。平衡二叉树详见。整体的思路:找到以每个结点为根结点的左右子树深度是否相差不大于1,从而判断是否是平衡的。

    所以,参考大神们的解法:

    递归大法。寻找最大深度的函数,可以使用层次遍历和最大深度中提及的方法。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isBalanced(TreeNode *root) 
        {
            if(root==NULL)  return true;
            if(abs(getDepth(root->left)-getDepth(root->right))>1)
                return false;
            return isBalanced(root->left)&&isBalanced(root->right);
        }
        
        int getDepth(TreeNode *root)
        {
            if(root==NULL)  return 0;
            return 1+max(getDepth(root->left),getDepth(root->right));
        }
    };

    改进,来源LeetCode。改进的思路:上面的算法,需要计算深度时,每个结点都要计算一遍。这样就会影响效率,若是发现子树不平衡,则不计算具体的深度,而是直接返回-1。优化后,对每个结点获得左右子树的深度后,若是,平衡的返回真实深度,不然就返回-1.

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isBalanced(TreeNode *root) 
    13     {
    14         if(root==NULL)   return true;
    15         int l=getHeight(root->left);
    16         int r=getHeight(root->right);
    17 
    18         if(l<0||r<0||abs(l-r)>1)    return false;
    19         return true;
    20     }
    21 
    22     int getHeight(TreeNode *root)
    23     {
    24         if(root==NULL)  return 0;
    25         int l=getHeight(root->left);
    26         int r=getHeight(root->right);
    27 
    28         if(l<0||r<0||abs(l-r)>1)    return -1;  //表示不平衡的情况
    29         return max(l,r)+1;
    30     }
    31 };
  • 相关阅读:
    Jenkins-------初探
    python--可迭代对象、迭代器和生成器
    python——模块、标准库、第三方模块安装
    python --装饰器通俗讲解
    python--函数、参数、名称空间与作用域、匿名函数、内置函数、闭包
    python--文件操作
    python--基础3(流程语句)
    python--基础2 (数据类型及应用)
    python--基础1(pip,虚拟环境、python编写规范)
    文本处理三剑客简介(grep、awk、sed)
  • 原文地址:https://www.cnblogs.com/love-yh/p/6999923.html
Copyright © 2020-2023  润新知