I am really confused about finding an element in a binary tree.
Question: When we say, search an element in a binary tree, maximum, in this case, do we assume that the tree is sorted???
If not, take a look at the below code, I got it from a book and almost every online URL suggests a similar pattern
int FindMaxNmb(BinaryTreeNode root)
{
int root_val, left, right, max;
if(root != null)
{
root_val = root.getData();
//recursion - this is what I don't understand
/*
* This code would have made sense if the binary tree contained
* Sorted elements, like The left subtree of a node contained
* Only nodes with keys less than the node's key The right subtree
* of a node contained only nodes with keys greater
* than the node's key.
* */
left = FindMaxNmb(root.getLeft());
right = FindMaxNmb(root.getRight());
//Find max number
if(left > right)
{
max = left;
}
else
{
max = right;
}
if(root_val > max)
{
max = root_val;
}
}
return max;
}
What i don't understand : take this recursion for instance
left = FindMaxNmb(root.getLeft()); this will go on calling unless it reaches the leftmost bottom leaf and then assigns the value, same is with getRight()....but this thing only works for the leftmost node having 2 children...how does it check the value of remaining nodes (I am assuming that binary tree is not sorted)
I know I am missing something very obvious here...please help!!
