题目描述
判断给定的二叉树是否是平衡的
在这个问题中,定义平衡二叉树为每个节点的左右两个子树高度差的绝对值不超过1的二叉树
代码
public static boolean isBalanced (TreeNode root) {if(root==null)return true;if(Math.abs(getDepth(root.left)-getDepth(root.right))>1) {return false;}return isBalanced(root.left)&&isBalanced(root.right);}public static int getDepth(TreeNode root) {if(root==null)return 0;int left = getDepth(root.left)+1;int right = getDepth(root.right)+1;return left>right?left:right;}
