解题思路:
递归判断左子树的高度与右子树的高度之差是否大于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.
AC解,C++代码,菜鸟一个,请大家多多指正
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int treeHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return 1 + max(treeHeight(root->left), treeHeight(root->right));
}
bool isBalanced(TreeNode* root) {
if (root == NULL) {
return true;
}
int diff = treeHeight(root->left) - treeHeight(root->right);
if (diff >= -1 && diff <= 1) {
return isBalanced(root->left) && isBalanced(root->right);
}
return false;
}
};
本文介绍了一种通过递归计算二叉树高度来判断其是否为平衡二叉树的方法,并提供了C++实现代码。平衡二叉树定义为任意节点的左右子树深度差不超过1的二叉树。
239

被折叠的 条评论
为什么被折叠?



