public static void main(String[] args) {
   // balanced binary tree test
   // 3
   // 2 5
   // 1 4 6
   BinaryTreeNode<Integer> tree = new BinaryTreeNode<>();
   tree.setLeft(new BinaryTreeNode<Integer>());
   tree.getLeft().setLeft(new BinaryTreeNode<Integer>());
   tree.setRight(new BinaryTreeNode<Integer>());
   tree.getRight().setLeft(new BinaryTreeNode<Integer>());
   tree.getRight().setRight(new BinaryTreeNode<Integer>());
   assert (isBalanced(tree));
   System.out.println(isBalanced(tree));
   tree = new BinaryTreeNode<>();
   tree.setLeft(new BinaryTreeNode<Integer>());
   tree.getLeft().setLeft(new BinaryTreeNode<Integer>());
   assert (!isBalanced(tree));
   System.out.println(isBalanced(tree));
 }
Пример #2
0
  private static boolean areKeysInRange(
      BinaryTreeNode<Integer> tree, Integer lower, Integer upper) {
    if (tree == null) {
      return true;
    } else if (Integer.compare(tree.getData(), lower) < 0
        || Integer.compare(tree.getData(), upper) > 0) {
      return false;
    }

    return areKeysInRange(tree.getLeft(), lower, tree.getData())
        && areKeysInRange(tree.getRight(), tree.getData(), upper);
  }
  private static BalanceStatusWithHeight CheckBalanced(BinaryTreeNode<Integer> tree) {
    if (tree == null) {
      return new BalanceStatusWithHeight(true, -1); // Base case.
    }

    BalanceStatusWithHeight leftResult = CheckBalanced(tree.getLeft());
    if (leftResult.balanced == false) {
      return leftResult; // Left subtree is not balanced.
    }
    BalanceStatusWithHeight rightResult = CheckBalanced(tree.getRight());
    if (rightResult.balanced == false) {
      return rightResult; // Right subtree is not balanced.
    }

    boolean isBalanced = Math.abs(leftResult.height - rightResult.height) <= 1;
    int height = Math.max(leftResult.height, rightResult.height) + 1;
    return new BalanceStatusWithHeight(isBalanced, height);
  }
Пример #4
0
 public static void main(String[] args) {
   // 3
   // 2 5
   // 1 4 6
   BinaryTreeNode<Integer> tree = new BinaryTreeNode<>(3);
   tree.setLeft(new BinaryTreeNode<>(2));
   tree.getLeft().setLeft(new BinaryTreeNode<>(1));
   tree.setRight(new BinaryTreeNode<>(5));
   tree.getRight().setLeft(new BinaryTreeNode<>(4));
   tree.getRight().setRight(new BinaryTreeNode<>(6));
   // should output true.
   assert isBinaryTreeBST(tree);
   System.out.println(isBinaryTreeBST(tree));
   // 10
   // 2 5
   // 1 4 6
   tree.setData(10);
   // should output false.
   assert !isBinaryTreeBST(tree);
   System.out.println(isBinaryTreeBST(tree));
   // should output true.
   assert isBinaryTreeBST(null);
   System.out.println(isBinaryTreeBST(null));
 }