• [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     const int unbalanceKids = -1;
     2 
     3     /**
     4      * count the number of children of node and itself
     5      */ 
     6     int height(TreeNode* node){
     7         
     8         int heightL = 0;
     9         if (node->left != NULL){
    10             heightL = height(node->left);
    11         }
    12         
    13         if(heightL == unbalanceKids){
    14             return unbalanceKids;
    15         }
    16         
    17         int heightR = 0;
    18         if (node->right != NULL){
    19             heightR = height(node->right);
    20         }
    21         
    22         if(heightR == unbalanceKids){
    23             return unbalanceKids;
    24         }
    25         
    26         if (abs(heightL - heightR) > 1){
    27             return unbalanceKids;
    28         }
    29         
    30         return max(heightL, heightR) + 1;
    31     }
    32 
    33     bool isBalanced(TreeNode* root) {
    34         
    35         if (root == NULL){
    36             return true;
    37         }
    38         
    39         int res  = height(root);
    40         if (res == unbalanceKids){
    41             return false;
    42         }
    43         
    44         return true;
    45     }
  • 相关阅读:
    css-博客样式初体验
    CSS-3D动画笔记
    Postman-断言
    CSS-2D动画笔记
    CSS-服务器端字体笔记
    CSS-宽度自适应和浏览器兼容笔记
    CSS-图片整合笔记
    CSS-锚点笔记
    Html-元素类型笔记
    Scrapy爬虫大战京东商城
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5119041.html
Copyright © 2020-2023  润新知