This is my first question ever at StackOverFlow: I am studying to interviews with the help of "Cracking the code interview" (5th Edition) book, and I was solving the next problem:
Implement a function to check if a binary tree is a binary search tree (Q 4.5 pg 86).
Before we move on, I would like just to remind you the difference between a Binary search tree to a simple Binary tree:
A 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 the right nodes.
So one of the solution the book offers is to scan the tree with In-Order traversal and on the fly to check if every node we visit is greater then the last one, and it assumes the tree can't have a 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, up here everything is good, but then the book quotes :
If you don't like the use of static variables, then you can tweak this code to use a wrapper class for the integer, as shown below:
Class WrapInt {
public int value;
}
After reading on wrapper class all over here and in other websites I just couldn't come to the conclusion, why and how should I use the wrapper class here instead of the static variable?