leetcode 39:balanced-binary-tree

题目描述

本题要求判断给定的二叉树是否是平衡二叉树
平衡二叉树的性质为: 要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过 1。
一颗树的高度指的是树的根节点到所有节点的距离中的最大值。
 
代码如下:
 1 int maxDepth(TreeNode* root)
 2     {
 3         if(root == NULL)
 4             return 0;
 5         return max(maxDepth(root->left),maxDepth(root->right)) + 1;
 6     }
 7     bool isBalanced(TreeNode* root) {
 8          if(root == NULL)
 9              return true;
10         if(abs(maxDepth(root->left) - maxDepth(root->right))> 1)
11             return false;
12         return isBalanced(root->left)&&isBalanced(root->right);
13     }

 

posted @ 2020-08-10 10:40  请叫我小小兽  阅读(108)  评论(0编辑  收藏  举报