How to implement a tree data-structure in Java?

前端 未结 24 2465
鱼传尺愫
鱼传尺愫 2020-11-22 00:27

Is there any standard Java library class to represent a tree in Java?

Specifically I need to represent the following:

  • The sub-tree at any node can have
相关标签:
24条回答
  • 2020-11-22 00:55

    If you're doing whiteboard coding, an interview, or even just planning to use a tree, the verbosity of these is all a little much.

    It should further be said that the reason a tree is not in there like, say, a Pair (about which the same could be said), is because you should be encapsulating your data in the class using it, and the simplest implementation looks like:

    /***
    /* Within the class that's using a binary tree for any reason. You could 
    /* generalize with generics IFF the parent class needs different value types.
     */
    private class Node {
      public String value;
      public Node[] nodes; // Or an Iterable<Node> nodes;
    }
    

    That's really it for an arbitrary width tree.

    If you wanted a binary tree it's often easier to use with named fields:

    private class Node { // Using package visibility is an option
      String value;
      Node left;
      Node right;
    }
    

    Or if you wanted a trie:

    private class Node {
      String value;
      Map<char, Node> nodes;
    }
    

    Now you said you want

    to be able to get all the children (some sort of list or array of Strings) given an input string representing a given node

    That sounds like your homework.
    But since I'm reasonably sure any deadline has now passed…

    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.List;
    
    public class kidsOfMatchTheseDays {
     static private class Node {
       String value;
       Node[] nodes;
     }
    
     // Pre-order; you didn't specify.
     static public List<String> list(Node node, String find) {
       return list(node, find, new ArrayList<String>(), false);
     }
    
     static private ArrayList<String> list(
         Node node,
         String find,
         ArrayList<String> list,
         boolean add) {
       if (node == null) {
         return list;
       }
       if (node.value.equals(find)) {
         add = true;
       }
       if (add) {
         list.add(node.value);
       }
       if (node.nodes != null) {
         for (Node child: node.nodes) {
           list(child, find, list, add);
         }
       }
       return list;
     }
    
     public static final void main(String... args) {
       // Usually never have to do setup like this, so excuse the style
       // And it could be cleaner by adding a constructor like:
       //     Node(String val, Node... children) {
       //         value = val;
       //         nodes = children;
       //     }
       Node tree = new Node();
       tree.value = "root";
       Node[] n = {new Node(), new Node()};
       tree.nodes = n;
       tree.nodes[0].value = "leftish";
       tree.nodes[1].value = "rightish-leafy";
       Node[] nn = {new Node()};
       tree.nodes[0].nodes = nn;
       tree.nodes[0].nodes[0].value = "off-leftish-leaf";
       // Enough setup
       System.out.println(Arrays.toString(list(tree, args[0]).toArray()));
     }
    }
    

    This gets you use like:

    $ java kidsOfMatchTheseDays leftish
    [leftish, off-leftish-leaf]
    $ java kidsOfMatchTheseDays root
    [root, leftish, off-leftish-leaf, rightish-leafy]
    $ java kidsOfMatchTheseDays rightish-leafy
    [rightish-leafy]
    $ java kidsOfMatchTheseDays a
    []
    
    0 讨论(0)
  • 2020-11-22 00:56

    You should start by defining what a tree is (for the domain), this is best done by defining the interface first. Not all trees structures are modifyable, being able to add and remove nodes should be an optional feature, so we make an extra interface for that.

    There's no need to create node objects which hold the values, in fact I see this as a major design flaw and overhead in most tree implementations. If you look at Swing, the TreeModel is free of node classes (only DefaultTreeModel makes use of TreeNode), as they are not really needed.

    public interface Tree <N extends Serializable> extends Serializable {
        List<N> getRoots ();
        N getParent (N node);
        List<N> getChildren (N node);
    }
    

    Mutable tree structure (allows to add and remove nodes):

    public interface MutableTree <N extends Serializable> extends Tree<N> {
        boolean add (N parent, N node);
        boolean remove (N node, boolean cascade);
    }
    

    Given these interfaces, code that uses trees doesn't have to care much about how the tree is implemented. This allows you to use generic implementations as well as specialized ones, where you realize the tree by delegating functions to another API.

    Example: file tree structure

    public class FileTree implements Tree<File> {
    
        @Override
        public List<File> getRoots() {
            return Arrays.stream(File.listRoots()).collect(Collectors.toList());
        }
    
        @Override
        public File getParent(File node) {
            return node.getParentFile();
        }
    
        @Override
        public List<File> getChildren(File node) {
            if (node.isDirectory()) {
                File[] children = node.listFiles();
                if (children != null) {
                    return Arrays.stream(children).collect(Collectors.toList());
                }
            }
            return Collections.emptyList();
        }
    }
    

    Example: generic tree structure (based on parent/child relations):

    public class MappedTreeStructure<N extends Serializable> implements MutableTree<N> {
    
        public static void main(String[] args) {
    
            MutableTree<String> tree = new MappedTreeStructure<>();
            tree.add("A", "B");
            tree.add("A", "C");
            tree.add("C", "D");
            tree.add("E", "A");
            System.out.println(tree);
        }
    
        private final Map<N, N> nodeParent = new HashMap<>();
        private final LinkedHashSet<N> nodeList = new LinkedHashSet<>();
    
        private void checkNotNull(N node, String parameterName) {
            if (node == null)
                throw new IllegalArgumentException(parameterName + " must not be null");
        }
    
        @Override
        public boolean add(N parent, N node) {
            checkNotNull(parent, "parent");
            checkNotNull(node, "node");
    
            // check for cycles
            N current = parent;
            do {
                if (node.equals(current)) {
                    throw new IllegalArgumentException(" node must not be the same or an ancestor of the parent");
                }
            } while ((current = getParent(current)) != null);
    
            boolean added = nodeList.add(node);
            nodeList.add(parent);
            nodeParent.put(node, parent);
            return added;
        }
    
        @Override
        public boolean remove(N node, boolean cascade) {
            checkNotNull(node, "node");
    
            if (!nodeList.contains(node)) {
                return false;
            }
            if (cascade) {
                for (N child : getChildren(node)) {
                    remove(child, true);
                }
            } else {
                for (N child : getChildren(node)) {
                    nodeParent.remove(child);
                }
            }
            nodeList.remove(node);
            return true;
        }
    
        @Override
        public List<N> getRoots() {
            return getChildren(null);
        }
    
        @Override
        public N getParent(N node) {
            checkNotNull(node, "node");
            return nodeParent.get(node);
        }
    
        @Override
        public List<N> getChildren(N node) {
            List<N> children = new LinkedList<>();
            for (N n : nodeList) {
                N parent = nodeParent.get(n);
                if (node == null && parent == null) {
                    children.add(n);
                } else if (node != null && parent != null && parent.equals(node)) {
                    children.add(n);
                }
            }
            return children;
        }
    
        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            dumpNodeStructure(builder, null, "- ");
            return builder.toString();
        }
    
        private void dumpNodeStructure(StringBuilder builder, N node, String prefix) {
            if (node != null) {
                builder.append(prefix);
                builder.append(node.toString());
                builder.append('\n');
                prefix = "  " + prefix;
            }
            for (N child : getChildren(node)) {
                dumpNodeStructure(builder, child, prefix);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:56

    Custom Tree implement of Tree without using the Collection framework. It contains different fundamental operation needed in Tree implementation.

    class Node {
    
        int data;
        Node left;
        Node right;
    
        public Node(int ddata, Node left, Node right) {
            this.data = ddata;
            this.left = null;
            this.right = null;      
        }
    
        public void displayNode(Node n) {
            System.out.print(n.data + " "); 
        }
    
    }
    
    class BinaryTree {
    
        Node root;
    
        public BinaryTree() {
            this.root = null;
        }
    
        public void insertLeft(int parent, int leftvalue ) {
            Node n = find(root, parent);
            Node leftchild = new Node(leftvalue, null, null);
            n.left = leftchild;
        }
    
        public void insertRight(int parent, int rightvalue) {
            Node n = find(root, parent);
            Node rightchild = new Node(rightvalue, null, null);
            n.right = rightchild;
        }
    
        public void insertRoot(int data) {
            root = new Node(data, null, null);
        }
    
        public Node getRoot() {
            return root;
        }
    
        public Node find(Node n, int key) {     
            Node result = null;
    
            if (n == null)
                return null;
    
            if (n.data == key)
                return n;
    
            if (n.left != null)
                result = find(n.left, key);
    
            if (result == null)
                result = find(n.right, key);
    
            return result;
        } 
    
        public int getheight(Node root){
            if (root == null)
                return 0;
    
            return Math.max(getheight(root.left), getheight(root.right)) + 1; 
        }
    
        public void printTree(Node n) {     
            if (n == null)
                return;
    
            printTree(n.left);
            n.displayNode(n);
            printTree(n.right);             
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 01:02
    public abstract class Node {
      List<Node> children;
    
      public List<Node> getChidren() {
        if (children == null) {
          children = new ArrayList<>();
        }
        return chidren;
      }
    }
    

    As simple as it gets and very easy to use. To use it, extend it:

    public class MenuItem extends Node {
      String label;
      String href;
      ...
    }
    
    0 讨论(0)
  • 2020-11-22 01:02
        // TestTree.java
    // A simple test to see how we can build a tree and populate it
    //
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    
    public class TestTree extends JFrame {
    
      JTree tree;
      DefaultTreeModel treeModel;
    
      public TestTree( ) {
        super("Tree Test Example");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
    
      public void init( ) {
        // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
        // DefaultTreeModel can use it to build a complete tree.
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
        DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
        DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");
    
        // Build our tree model starting at the root node, and then make a JTree out
        // of it.
        treeModel = new DefaultTreeModel(root);
        tree = new JTree(treeModel);
    
        // Build the tree up from the nodes we created.
        treeModel.insertNodeInto(subroot, root, 0);
        // Or, more succinctly:
        subroot.add(leaf1);
        root.add(leaf2);
    
        // Display it.
        getContentPane( ).add(tree, BorderLayout.CENTER);
      }
    
      public static void main(String args[]) {
        TestTree tt = new TestTree( );
        tt.init( );
        tt.setVisible(true);
      }
    }
    
    0 讨论(0)
  • 2020-11-22 01:03

    No answer mentions over-simplified but working code, so here it is:

    public class TreeNodeArray<T> {
        public T value;
        public final  java.util.List<TreeNodeArray<T>> kids =  new java.util.ArrayList<TreeNodeArray<T>>();
    }
    
    0 讨论(0)
提交回复
热议问题