如题:
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-
思路:
这道题算的上是比较简单的了,思路大概就是两层:- 递归判断每个节点
- 具体判断是每个节点的两个子树的深度比较
解题:
bool isBalanced(TreeNode* root) {
TreeNode *tempTreeNode = root;
if (tempTreeNode == NULL) {
return true;
}
if (abs(getMaxDeepth(tempTreeNode->left) - getMaxDeepth(tempTreeNode->right)) > 1) {
return false;
}
return isBalanced(tempTreeNode->left) && isBalanced(tempTreeNode->right);
}
int getMaxDeepth(TreeNode *treeNode) {
if (treeNode == NULL) {
return 0;
}
int left = getMaxDeepth(treeNode->left);
int right = getMaxDeepth(treeNode->right);
return (left > right ? left : right) + 1;
}