在二叉搜索树中查找最小元素(迭代和递归)

时间:2013-04-12 12:49:07

标签: java binary-search-tree

这是我使用两种不同方式在BST中查找最小搜索键的实现,我想确定我是否正确执行:

迭代

public T findSmallest ( BinarySearchTree<T> tree )

{ BinaryNode Node = new BinaryNode (tree.getDataRoot);

  if ( Node == null ) return null;

  while(Node.hasLeftChild()) Node = Node.getLeftChild;

return Node.getData(); } 

递归

public T findSmallest ( BinaryNode Node ) 

{ if (Node == null) return null;

  if(Node.getLeftChild()==null) return Node.getData(); 

  else 

  return findSmallest ( (Node.getLeftChild()) ; } 

1 个答案:

答案 0 :(得分:0)

看起来不错,我重新格式化了代码,希望我没有错过任何东西。

<强>迭代

public T FindSmallest(BinarySearchTree<T> tree){ 
  BinaryNode Node = new BinaryNode(tree.getDataRoot());
  if (Node == null) 
    return null;

  while(Node.hasLeftChild()) 
    Node = Node.getLeftChild();

  return Node.getData(); 
}

<强>递归

public T FindSmallest(BinaryNode Node){ 
  if (Node == null) 
    return null;

  if(Node.getLeftChild()==null) 
    return Node.getData(); 

  return findSmallest(Node.getLeftChild()); 
} 

您可能会对此感兴趣:Find kth smallest element in a binary search tree in Optimum way

相关问题