Q110. Balanced Binary Tree
分析
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:
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(treeHeight(root->left) - treeHeight(root->right)) >= 2) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
private:
int treeHeight(TreeNode* root){
if (!root) return 0;
return max(treeHeight(root->left), treeHeight(root->right))+1;
}
};Last updated