110. Balanced Binary Tree
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.
Subscribe to see which companies asked this question
初看题,以为是平衡一棵二叉树,结果是判断一棵二叉树是否是平衡二叉树,这样的话,我们只需要知道每个节点的高度就可以了。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int heightForNode(struct TreeNode *node){
if(node ==NULL){
return 0;
}
if(node->left==NULL&&node->right==NULL){
return 1;
}
int left_height=heightForNode(node->left);
int right_height=heightForNode(node->right);
return (left_height>right_height?left_height:right_height)+1;
}
bool isBalanced(struct TreeNode* root) {
if(root==NULL) return true;
if(abs(heightForNode(root->left)-heightForNode(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right))
return true;
return false;
}