Find k-unbalanced nodes
EPI Solution
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/KBalancedBinaryTreeTemplate.java
private static <T> Pair<BinaryTree<T>, Integer> findNonKBalancedNodeHelper(
BinaryTree<T> n, int k) {
// Empty tree.
if (n == null) {
return new Pair<BinaryTree<T>, Integer>(null, 0);
}
// Early return if left subtree is not k-balanced.
Pair<BinaryTree<T>, Integer> L = findNonKBalancedNodeHelper(n.getLeft(), k);
if (L.getFirst() != null) {
return L;
}
// Early return if right subtree is not k-balanced.
Pair<BinaryTree<T>, Integer> R = findNonKBalancedNodeHelper(n.getRight(), k);
if (R.getFirst() != null) {
return R;
}
int nodeNum = L.getSecond() + R.getSecond() + 1; // # of nodes in n.
if (Math.abs(L.getSecond() - R.getSecond()) > k) {
return new Pair<BinaryTree<T>, Integer>(n, nodeNum);
}
return new Pair<BinaryTree<T>, Integer>(null, nodeNum);
}
private static <T> BinaryTree<T> findNonKBalancedNode(BinaryTree<T> n, int k) {
return findNonKBalancedNodeHelper(n, k).getFirst();
}
EPI Solution
https://github.com/epibook/epibook.github.io/blob/master/solutions/java/src/main/java/com/epi/KBalancedBinaryTreeTemplate.java
private static <T> Pair<BinaryTree<T>, Integer> findNonKBalancedNodeHelper(
BinaryTree<T> n, int k) {
// Empty tree.
if (n == null) {
return new Pair<BinaryTree<T>, Integer>(null, 0);
}
// Early return if left subtree is not k-balanced.
Pair<BinaryTree<T>, Integer> L = findNonKBalancedNodeHelper(n.getLeft(), k);
if (L.getFirst() != null) {
return L;
}
// Early return if right subtree is not k-balanced.
Pair<BinaryTree<T>, Integer> R = findNonKBalancedNodeHelper(n.getRight(), k);
if (R.getFirst() != null) {
return R;
}
int nodeNum = L.getSecond() + R.getSecond() + 1; // # of nodes in n.
if (Math.abs(L.getSecond() - R.getSecond()) > k) {
return new Pair<BinaryTree<T>, Integer>(n, nodeNum);
}
return new Pair<BinaryTree<T>, Integer>(null, nodeNum);
}
private static <T> BinaryTree<T> findNonKBalancedNode(BinaryTree<T> n, int k) {
return findNonKBalancedNodeHelper(n, k).getFirst();
}