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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.