2012-12-07 51 views
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); 
    } 
} 
+2

你是什么意思“它不工作”?请提供有关您遇到的问题的更多详细信息。 –

回答

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()); 
    } 
}