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.
/**
* 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 depth(TreeNode* r){
return r == NULL ? 0:(1+ max(depth(r->left), depth(r->right)));
}
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
int lh = depth(root->left);
int rh = depth(root->right);
return abs(lh-rh)<=1 && isBalanced(root->left) && isBalanced(root->right);
}
};
下面只需要遍历所有节点一次
/**
* 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:
bool isBalanced(TreeNode* root) {
int d = 0;
return isBalanced(root, d);
}
private:
bool isBalanced(TreeNode* r, int &depth){
if(r == NULL){
depth = 0;
return true;
}
int lh, rh;
if(isBalanced(r->left, lh) && isBalanced(r->right, rh)){
if(abs(lh - rh) <= 1){
depth = max(lh, rh) + 1;
return true;
}
}
return false;
}
};