判断是否为AVL树
时间复杂度:O(n)
// 判断是否为AVL树 public int isAVL(TreeNode node) { if (node == null) { return 0; } int left = isAVL(node.left); if (left == -1) { return -1; } int right = isAVL(node.right); if (right == -1) { return -1; } int diff = left - right; if (Math.abs(diff) > 1) { return -1; } else { return Math.max(left, right) + 1; } } public static boolean isBalanced(TreeNode root) { if (isAVL(root) == -1) { return false; } else { return true; } }
不要让执行的勤奋掩盖思考的懒惰!