Reverse A Binary Tree (Left to Right) [closed]

You can use recursion. We swap the left and right child of a node, in-place, and then do the same for its children: static void reverseTree(final TreeNode root) { final TreeNode temp = root.right; root.right = root.left; root.left = temp; if (root.left != null) { reverseTree(root.left); } if (root.right != null) { reverseTree(root.right); } } … Read more

Why use binary search if there’s ternary search?

Actually, people do use k-ary trees for arbitrary k. This is, however, a tradeoff. To find an element in a k-ary tree, you need around k*ln(N)/ln(k) operations (remember the change-of-base formula). The larger your k is, the more overall operations you need. The logical extension of what you are saying is “why don’t people use … Read more

B trees vs binary trees

Algorithmic complexity is the same, since O(logb n) = O(c log n) = O(log n) but the constant factors, which are hidden in big-O notation, could vary noticeably, depending on implementation and hardware. B-trees were designed for platter hard disks, which have a large access time (moving the head into position) after which an entire … Read more

Red-Black Trees

Red Black trees are good for creating well-balanced trees. The major problem with binary search trees is that you can make them unbalanced very easily. Imagine your first number is a 15. Then all the numbers after that are increasingly smaller than 15. You’ll have a tree that is very heavy on the left side … Read more

Check if a binary tree is a mirror image or symmetric

How about calling mirrorEquals(root.left, root.right) on the following function :- boolean mirrorEquals(BTree left, BTree right) { if (left == null || right == null) return left == null && right == null; return left.value == right.value && mirrorEquals(left.left, right.right) && mirrorEquals(left.right, right.left); } Basically compare the left subtree and inverted right subtree, drawing an imaginary … Read more