赞
踩
/** * code110 */ public class code110 { public static boolean isBalanced(TreeNode root) { // 它是一棵空树 if (root == null) { return true; } // 它的左右两个子树的高度差的绝对值不超过1 if (Math.abs(maxDepth(root.left) - maxDepth(root.right)) > 1) { return false; } // 左右两个子树都是一棵平衡二叉树 if (!isBalanced(root.left)) { return false; } if (!isBalanced(root.right)) { return false; } return true; } public static int maxDepth(TreeNode root) { if (root == null) { return 0; } return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } public static void main(String[] args) { Integer nums1[] = { 3, 9, 20, null, null, 15, 7 }; TreeNode tree1 = ConstructTree.constructTree(nums1); System.out.println("***************************************"); TreeOperation.show(tree1); boolean flag1 = isBalanced(tree1); System.out.println(flag1); System.out.println("***************************************"); Integer nums2[] = { 1, 2, 2, 3, 3, null, null, 4, 4 }; TreeNode tree2 = ConstructTree.constructTree(nums2); TreeOperation.show(tree2); boolean flag2 = isBalanced(tree2); System.out.println(flag2); System.out.println("***************************************"); Integer nums3[] = { 1, 2, 2, 3, null, null, 3, 4, null, null, 4 }; TreeNode tree3 = ConstructTree.constructTree(nums3); TreeOperation.show(tree3); boolean flag3 = isBalanced(tree3); System.out.println(flag3); System.out.println("***************************************"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。