查找第二小节点的java二叉搜索树
我试图使该方法找到第二个最小的节点 但是,当我找到最小的节点(没有正确的节点)时 我应该返回节点的父节点,使其最小。然而,我没有办法让它变成那样。。。请帮帮我,伙计们查找第二小节点的java二叉搜索树,java,binary-search-tree,Java,Binary Search Tree,我试图使该方法找到第二个最小的节点 但是,当我找到最小的节点(没有正确的节点)时 我应该返回节点的父节点,使其最小。然而,我没有办法让它变成那样。。。请帮帮我,伙计们 public StringNode secondSmallest() { return secondSmallest(root); } private StringNode secondSmallest(StringNode x) { if(x==null); //base case: if the le
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());
}
示例代码
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);
}
}
公共接口树{
/**
*查找树中第n个最小的元素
*
*@param nth
*@return树中第n个最小元素
*/
公共K FindSallest(int N);
}
@凌驾
公共K FindSallest(int nth){
节点迭代器=根;
返回traverseLeftParentRight(迭代器,新的AtomicInteger(第n个));
}
私有K traverseLeftParentRight(节点迭代器,原子整数n){
if(null==迭代器| | n.get()==0){
返回null;
}
K值=traverseLeftParentRight(iterator.left,n);
//在左子树本身中找到
if(null!=值){
返回值;
}
if(n.decrementAndGet()==0){
返回iterator.key;
}
//签入右子树
返回traverseLeftParentRight(iterator.right,n);
}
公共静态void main(字符串[]args){
//创建一个BST
比较器比较器=整数比较器();
Tree-Tree=新的二进制搜索树(比较器);
填充数据(树);
System.out.println(“4thlest元素”+tree.findsmalest(4));
}
私有静态void fillData(Treetree){
tree.put(5,“value-5”);
对于(int i=0;i)您的版本一直遍历左侧,然后返回一个元素。这不起作用,因为它不遵循BST的不变量。您熟悉吗?谢谢您的评论。我目前正在学校学习BST。您能解释一下吗?如果您能再找到一个解决方案,我会告诉您NSE:我想这不是我要找的,我喜欢让一个方法只接受一个参数(节点x),并使用递归的方式找出左二最小值。if(n.decrementAndGet()==0){return iterator.key;}
我不明白这部分工具书在“Amazon我来了”中的解决方案。您还必须传递第二个参数才能知道第N个最小的元素。传递N作为2以获得第二个最小值该整数应该是AtomicInteger?或者它可以是正则整数?您将传递普通整数。该整数在公共K findsmalest(int Nth){Node iterator=root;返回traverseLeftParentRight中转换为AtomicInteger(迭代器,新的原子整数(n));}