平衡二叉树
自下而上
后序遍历加剪枝
/**
* 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 checkhigh(TreeNode* node){
if(node==nullptr)
return 0;
int lhigh=checkhigh(node->left);
int rhigh=checkhigh(node->right);
if(lhigh==-1)
return -1;
if(rhigh==-1)
return -1;
int high=max(lhigh,rhigh)+1;
return abs(lhigh-rhigh)<2? high:-1;
}
bool isBalanced(TreeNode* root) {
if(checkhigh(root)==-1)
return false;
return true;
}
};
借鉴别的博主,自上而下,即检查当前父节点,以及左右节点是否各自满足条件
存在大量重复运算
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
private int depth(TreeNode root) {
if (root == null) return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}