• leetcode 110. 平衡二叉树


    给定一个二叉树,判断它是否是高度平衡的二叉树。

    本题中,一棵高度平衡二叉树定义为:

    一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

    示例 1:

    给定二叉树 [3,9,20,null,null,15,7]

        3
       / 
      9  20
        /  
       15   7

    返回 true 。

    示例 2:

    给定二叉树 [1,2,2,3,3,null,null,4,4]

           1
          / 
         2   2
        / 
       3   3
      / 
     4   4
    

    返回 false 。

     1 /**
     2  * Definition for a binary tree node.
     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     int getHeight(TreeNode* root){
    13         if(root == NULL) return 0;
    14         int l = getHeight(root->left);
    15         int r = getHeight(root->right);
    16         return l > r ? l+1 : r+1;
    17     }
    18     bool isBalanced(TreeNode* root) {
    19         if(root == NULL) return true;
    20         if(getHeight(root->left) - getHeight(root->right) > 1) return false;
    21         else if(getHeight(root->right) - getHeight(root->left) > 1) return false;
    22         else return isBalanced(root->left) && isBalanced(root->right);
    23     }
    24 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    第一阶段SCRUM冲刺10
    第一阶段SCRUM冲刺09
    第一阶段SCRUM冲刺08
    单词统计续
    第十一周学习报告
    第一阶段SCRUM冲刺07
    第一阶段SCRUM冲刺06
    第一阶段SCRUM冲刺05
    十天冲刺08
    十天冲刺07
  • 原文地址:https://www.cnblogs.com/mr-stn/p/8951156.html
Copyright © 2020-2023  润新知