110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
平衡二叉树:左右子树高度差不大于1
条件:左子树是平衡树,右子树是平衡树,左右子树的高度差不高于1
信息:是否平衡,高度
class Solution { public boolean isBalanced(TreeNode root) { return process(root).isBalanced; } public Info process(TreeNode node){ if(node==null){ return new Info(true,0); } Info leftInfo=process(node.left); Info rightInfo=process(node.right); int height=Math.max(leftInfo.height,rightInfo.height)+1; int diffH=Math.abs(leftInfo.height-rightInfo.height); boolean isBalanced=false; if(leftInfo.isBalanced&& rightInfo.isBalanced && diffH<2){ isBalanced=true; } return new Info(isBalanced,height); } public class Info{ public boolean isBalanced; public int height; public Info(boolean b,int height){ this.isBalanced=b; this.height=height; } } }