package cookie; public class BTreeDepthIsBalanced { int depth(BNode head) { if (head == null) { return 0; } int left = depth(head.left); int right = depth(head.right); return left > right ? left + 1 : right + 1; } boolean isBalanced(BNode head) { if (head == null) { return true; } int left = depth(head.left); int right = depth(head.right); int diff = left - right; if (diff > 1 || diff < -1) { return false; } return isBalanced(head.left) && isBalanced(head.right); } } class BNode { int value; BNode left; BNode right; }
以上每个节点被遍历多次。