How to Serialize Binary Tree

All those articles talk mostly about the serialization part. The deserialization part is slightly tricky to do in one pass. I have implemented an efficient solution for deserialization too. Problem: Serialize and Deserialize a binary tree containing positive numbers. Serialization part: Use 0 to represent null. Serialize to list of integers using preorder traversal. Deserialization … Read more

Finding if a Binary Tree is a Binary Search Tree [duplicate]

It’s a pretty well-known problem with the following answer: public boolean isValid(Node root) { return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } private boolean isValidBST(Node node, int l, int h) { if(node == null) return true; return node.value > l && node.value < h && isValidBST(node.left, l, node.value) && isValidBST(node.right, node.value, h); } The recursive call makes sure … Read more

Tail recursive function to find depth of a tree in Ocaml

You can trivially do this by turning the function into CPS (Continuation Passing Style). The idea is that instead of calling depth left, and then computing things based on this result, you call depth left (fun dleft -> …), where the second argument is “what to compute once the result (dleft) is available”. let depth … Read more

Printing BFS (Binary Tree) in Level Order with Specific Formatting

Just build one level at a time, e.g.: class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def traverse(rootnode): thislevel = [rootnode] while thislevel: nextlevel = list() for n in thislevel: print n.value, if n.left: nextlevel.append(n.left) if n.right: nextlevel.append(n.right) print thislevel = nextlevel t = Node(1, Node(2, Node(4, … Read more

Can max/min heap trees contain duplicate values?

Yes, they can. You can read about this in ‘Introduction to Algorithms’ (by Charles E. Leiserson, Clifford Stein, Thomas H. Cormen, and Ronald Rivest). According to the definition of binary heaps in Wikipedia: All nodes are either [greater than or equal to](max heaps) or [less than or equal to](min heaps) each of its children, according … Read more