我对在二叉树中查找元素感到非常困惑。
问题: 当我们说,在二叉树中搜索一个元素,特别是最大值时,我们是否假定该树已排序?
如果没有,看一下下面的代码,我从一本书上找到了它,几乎每个在线网址都建议使用类似的模式。
int FindMaxNmb(BinaryTreeNode root)
{
int root_val,left,right,max;
if(root!=null)
{
root_val = root.getData();
//recursion - this is what i dont understand
/*
*
* This code would have made sense if 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 nmbr
if(left > right)
{
max = left;
}
else
{
max = right;
}
if(root_val > max)
{
max = root_val;
}
}
return max;
}
我不理解的是:以递归为例,
left = FindMaxNmb(root.getLeft());
这将一直调用直到它到达最左下角的叶子节点,然后赋值,getRight()
同样如此......但这个东西只对拥有2个孩子的最左端节点有效...那么如何检查其余节点的值(我假设二叉树没有排序)?我知道我在这里错过了一些非常明显的东西......请帮忙!