0

我无法找到二叉搜索树的最小元素。我已经完成了一些代码,但它不起作用。

public T getMinElement(TreeNode<T> node) {
    //TODO: implement this
    if (node == null){
        return null;
    }
     if (node.getLeftChild() == null){
        return (T) node;
     }
     else{
        return getMinElement(node);
  }
}
4

1 回答 1

6

你快到了!你只需要在你的二叉搜索树的左子节点上递归(总是保证更小)。你也有一些语法错误,我修复了。

public <T> T getMinElement(TreeNode<T> node) {
  if (node == null){
    return null;
  }
  if (node.getLeftChild() == null){
    return node.getData(); // or whatever your method is
  } else{
    return getMinElement(node.getLeftChild());
  }
}
于 2012-12-07T01:52:23.403 回答