简体   繁体   English

Java二进制搜索树找到第二个最小的节点

[英]java binary search tree finding second smallest node

I am trying to make the method find the second smallest node However, when I found the smallest node(which doesn't have right node) I should return the parent of the node to make it "second" smallest. 我试图使该方法找到第二个最小的节点,但是,当我找到最小的节点(没有正确的节点)时,我应该返回该节点的父节点以使其成为“第二个”最小节点。 However, I don't have an idea to make it like that... please help me out guys 但是,我不知道要这样做吗...请帮帮我

public StringNode secondSmallest() {
    return secondSmallest(root);
}

private StringNode secondSmallest(StringNode x) {
    if(x==null);
    //base case: if the left node is null -> smallest
    if (x.getLeft()==null) {        
        //if there is only right child
        if(x.getRight()!=null) {
            return x.getRight();
        }
        //when there is no right node and smallest
        return x;
    }
    //keep finding left node
    else
        return secondSmallest(x.getLeft());

}

Sample code. 样例代码。

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

Read this Nth Samllest Element article for complete details. 阅读此Nth Samllest Element文章以获取完整详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM