做题不要想当然。平衡二叉树不单单是根节点树平衡,左右子树也要平衡,需要逐一判断
public class Solution { boolean res = true; public boolean IsBalanced_Solution(TreeNode root) { preorder(root); return res; } private void preorder(TreeNode node) { if (node != null) { if (!judge(node)) { res = false; return; } preorder(node.left); preorder(node.right); } } private boolean judge (TreeNode node) { if (Math.abs(treeDepth(node.left)-treeDepth(node.right)) <= 1) { return true; } else { return false; } } private int treeDepth(TreeNode treeNode) { if (treeNode == null) { return 0; } return Math.max(treeDepth(treeNode.left),treeDepth(treeNode.right)) + 1; } }