【leetcode 二叉树平衡判断】

时间:2022-12-17 17:27:45

1、题目

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

2、分析

用递归法
 一棵树平衡的条件:左子树平衡&&右子树平衡&&左右子树高度差不超过1

3、代码

<span style="font-size:18px;">/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*递归法
一棵树平衡的条件:左子树平衡&&右子树平衡&&左右子树高度差不超过1
*/
class Solution {
public:
bool isBalanced(TreeNode *root) {
if(!root) return true;
return isBalanced(root->left) && isBalanced(root->right) && abs(treeDepth(root->left)-treeDepth(root->right))<2 ;
}
private:
int treeDepth(TreeNode *root) //求树的高度 又是递归
{
if(!root) return 0;
return max(treeDepth(root->left),treeDepth(root->right))+1;
}
};</span>