java二叉搜索树查找第二个最小节点

时间:2015-09-21 03:39:51

标签: java binary-search-tree

我试图让方法找到第二个最小的节点 但是,当我找到最小的节点(它没有正确的节点) 我应该返回节点的父节点以使其成为第二个节点。最小。但是,我没有想法让它成为那样......请帮助我的人

{{1}}

1 个答案:

答案 0 :(得分:2)

示例代码。

public interface Tree<K, V> {
       /**
     * Find the nth smallest element in the tree
     * 
     * @param nth
     * @return nth smallest element in the tree
     */
    public K findSmallest(int nth);
}

@Override


 public K findSmallest(int nth) {
    Node iterator = root;
    return traverseLeftParentRight(iterator, new AtomicInteger(nth));
  }



private K traverseLeftParentRight(Node iterator, AtomicInteger nth) {
    if (null == iterator || nth.get() == 0) {
      return null;
    }
    K value = traverseLeftParentRight(iterator.left, nth);
    // Found in the left subtree itself
    if (null != value) {
      return value;
    }
    if (nth.decrementAndGet() == 0) {
      return iterator.key;
    }
    // Check in the right subtree
    return traverseLeftParentRight(iterator.right, nth);
  }



  public static void main(String[] args) {
      // Create a BST
      Comparator comparator = integerComparator();
      Tree tree = new BinarySearchTree(comparator);
      fillData(tree);
      System.out.println("4thlest element " + tree.findSmallest(4));
   }

private static void fillData(Treetree) {
  tree.put(5, "value-5");
  for (int i = 0; i <= 10; i++) {
   tree.put(i, "value-" + i);
  }
 }

阅读此Nth Samllest Element文章了解详情。