leetcode-110 平衡二叉树
平衡二叉树要求所有节点的左右子树的高度差小于1,因此,只需在遍历的时候返回其左右子树的深度。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private boolean flag = true;
public int checkTree(TreeNode root, int depth){
if (root == null|| ! flag) return depth;
int leftDepth = checkTree(root.left, depth + 1);
int rightDepth = checkTree(root.right, depth + 1);
// 计算高度差
if (Math.abs(leftDepth - rightDepth) > 1){
flag = false;
return 0;
}
// 返回其左右子树最大的深度作为当前节点的深度
return Math.max(leftDepth, rightDepth);
}
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
checkTree(root, 0);
return flag;
}
}