110. 平衡二叉树
顶到底 效率太低了
class Solution { public boolean isBalanced(TreeNode root) { if(root == null)return true; if(Math.abs(func(root.left)-func(root.right))>1) return false; return isBalanced(root.left)&&isBalanced(root.right); } public int func(TreeNode node){ if(node==null)return 0; else return Math.max(func(node.left)+1,func(node.right)+1); } }
底到顶
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isBalanced(TreeNode root) { return recur(root) != -1; } private int recur(TreeNode root) { if(root == null) return 0; int left_value = recur(root.left); if(left_value == -1) return -1; int right_value = recur(root.right); if(right_value == -1) return -1; if(Math.abs(left_value-right_value)>1) return -1; return Math.max(left_value,right_value)+1; } }