简体   繁体   中英

Tree nodes holding linkedlist

Ok, what I am trying to do is have each node of a BSTree hold a linkedlist.
For example:

Node B holds - bill, buff, blank
Then its left child A holds - ant, art, app
And its right child C holds - cat, can crib
And so on;

This is what I have so far but I am not sure that this is the best way to do this

public class BSTreeDic {
public class LinkNode{
    LinkNode word;
    LinkNode next;
    public void add(LinkNode wd, LinkNode def){
        if (word==null){
            word=wd;
            next=def;
        }else{
            LinkNode currentNode = word;
            while(currentNode.next!=null){
                currentNode=currentNode.next;
            }
            currentNode.next=def;
            next=currentNode.next;
        }
    }
}
public class Node{
    LinkNode word;
    Node left;
    Node right;
    Node(LinkNode wd, LinkNode def){
        word = new LinkNode();
        word.add(wd, def);
        left=right=null;
    }

}
}

If you don't want to use (and import) the class java.util.LinkedList:

public class LinkNode {  //Please begin class names with caps
    String word;
    LinkNode next = null;
    LinkNode(String w) {
        word = w;
    }
}

public class Node {
    LinkedList<Node> word;
    Node left;
    Node right;

    Node(String wd, String def) {
        word = new LinkedList<Node>();
        word.add(def);
        word.add(wd);
    }
}

Also, for a Binary Search Tree, if search is alphabetical then the left children should be earlier in the alphabet than their parents.

You should also probably have add() and remove() methods for LinkNode and Node, to add and remove nodes. One possibility is to call Node TreeNode and make LinkNode and TreeNode subclasses of class Node.

You are pretty close. The only think I would suggest adding is an actual LinkedList object that holds a reference to the list head and allows for addition, deletion, retrieval, etc

public class LinkedList {
  ListNode head;
  ListNode tail;

  public void addElement(ListNode ln) {
    if (head == null) {
      head = ln;
      tail = ln;
    }
    else {
      ListNode currentNode = head;
      while(currentNode.next!= null) {
        currentNode = currentNode.next;
      }
      currentNode.next = ln;
      tail = currentNode.next;
    }
  }
}

The other methods are very similar. You just need to remember that linkedlist operations are usually associated with list traversal. Hope this helps.

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.

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