【发布时间】:2014-03-05 18:02:20
【问题描述】:
我真的很困惑在binary tree 中找到一个元素。
问题:当我们说,在二叉树中搜索一个元素时,在这种情况下是最大值,我们是否假设树是排序的???
如果没有,请看下面的代码,我从一本书中得到它,几乎每个在线 url 都在暗示类似的模式
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;
}
我不明白的: 以这个 recursion 为例
left = FindMaxNmb(root.getLeft()); 这将继续调用,除非它到达最左边的底部叶子然后分配值,getRight() 也是如此......但是这个东西只适用于有 2 个孩子的最左边的节点......它如何检查剩余节点的值(我假设二叉树没有排序)
我知道我在这里遗漏了一些非常明显的东西......请帮忙!
【问题讨论】:
-
ok..让我说得简单点...在我发布的代码中,它在 BST 而不是 BT 的假设下搜索最大元素...对吗??
标签: java search recursion tree binary-tree