This is my first question at StackOverFlow: I study the interview using the book “Cracking the code interview” (5th edition) and I solved the following problem:
Implement a function to check if the binary tree is a binary search tree (Q 4.5 p. 86).
Before moving on, I would just remind you of the difference between a binary search tree and a simple binary tree:
The binary search tree imposes the condition that for all nodes the left children are less than or equal to the current node, which is less than all regular nodes.
So, one of the solutions that the book offers is to scan the tree using an In-Order and on-the-fly traversal to check if each node we visit is larger and the last one, and assumes that the tree cannot have duplicate values:
public static int last_printed = Integer.MIN_VALUE; public static boolean checkBST(TreeNode n) { if(n == null) return true; // Check / recurse left if (!checkBST(n.left)) return false; // Check current if (n.data <= last_printed) return false; last_printed = n.data; // Check / recurse right if (!checkBST(n.right)) return false; return true; // All good! }
Now, everything is fine here, but then the book quotes:
If you don't like static variables, you can configure this code to use a wrapper class for an integer, as shown below:
Class WrapInt { public int value; }
After reading the wrapper class in all of this and on other sites, I just couldn’t conclude why and how should I use a wrapper class here instead of a static variable?
source share