How to implement a tree data-structure in Java?

前端 未结 24 2518
鱼传尺愫
鱼传尺愫 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: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);             
        }
    
    }
    

提交回复
热议问题