将节点插入BST时无限循环

时间:2017-05-13 04:27:53

标签: java data-structures binary-search-tree

我有一个根据字母顺序在BST中插入节点的方法,但是当我比较2个字符串时我有一个无限循环我认为当它通过比较时值永远不会改变所以它比较再次使用相同的值导致无限循环。我认为auxT节点没有使用递归方法更新值,因此它反复比较相同的值。

class BST {

    BSTNode root;

    public BST() {
        root = null;
    }

    BSTNode aux = new BSTNode();

    BSTNode insertNames(BSTNode T , int data, String name, double salary) {
        if (root == null) {
            T = new BSTNode();  
            T.setName(name);
            root = T;
        } else {
            aux = root;

            if (name.compareTo(aux.getName()) < 0)
                aux.setLeft(insertNames(aux.getLeft(),data, name, salary));
            else if (name.compareTo(aux.getName()) >= 0)
                aux.setRight(insertNames(aux.getRight(),data, name, salary));
        }

        return T;
    }    
}

class Main{
public static void main(String[] args){

        BST alpha=new BST();
        BSTNode root = new BSTNode();
        alpha.insertNames(root, 0, "Roy", 0);
        alpha.insertNames(root, 0, "Joseph", 0);
}
}

2 个答案:

答案 0 :(得分:0)

请以递归结束逻辑返回节点。

       /* If the tree is empty, return a new node */
if (root == null) {
    root = new BSTNode();
    root.setName(name);
    return root;
}

/* Otherwise, recur down the tree */
if (name.compareTo(root.getName()) < 0)
    root.setLeft(insertNames(root.getLeft(), data, name, salary));
else if (name.compareTo(aux.getName()) >= 0)
    root.setRight(insertNames(root.getRight(), data, name, salary));

/* return the (unchanged) node pointer */
return root;

或者它可以以迭代的方式解决

 if (localRoot == null) {
    newNode = new Node < V > (value, null);
    root = newNode;
    size++;
    return true;
}
if (comparator != null) {
//Some code
} else {
    Comparable << ? super V > v = (Comparable << ? super V > ) value;
    while (localRoot != null) {
        parent = localRoot;
        cmp = v.compareTo(localRoot.getValue());
        if (cmp < 0) {
            localRoot = localRoot.getLeftChield();
        } else if (cmp > 0) {
            localRoot = localRoot.getRightChield();
        } else {
            localRoot.incrementBy(nCopies);
            return true;
        }
    }
    newNode = new Node < V > (value, parent);
    if (cmp < 0) {
        parent.setLeftChield(newNode);
    } else if (cmp > 0) {
        parent.setRightChield(newNode);
    }
    size++;
    return true;
}
return false;

答案 1 :(得分:0)

// add this line at the top of the file, import it
import {AndroidFullScreen} from "@ionic-native/android-full-screen";
...
constructor(public platform: Platform,
            public statusBar: StatusBar,
            public splashScreen: SplashScreen,
            public androidFullScreen: AndroidFullScreen) {

  // show statusbar
  this.androidFullScreen.isSupported()
    .then(() => this.androidFullScreen.showSystemUI());

  // style statusbar and hide splash
  this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
  });
}
...