Tree Data Structure in Java

The Program is the simple demonstration of tree data structure in Java with GUI. The simplest form of tree is binary tree and it consists of node or (root node) and left and right sub-tree. Both the sub-tree are themselves binary tree.

Source Code 

package TempClass;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TestTree extends JFrame {

  JTree myTree;

  DefaultTreeModel myModel;

  public TestTree() {
    super("Tree Test Example");
    setSize(400, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public void init() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    myModel = new DefaultTreeModel(root);
    myTree = new JTree(myModel);

    myModel.insertNodeInto(subroot, root, 0);
    
    subroot.add(leaf1);
    root.add(leaf2);

    getContentPane().add(myTree, BorderLayout.CENTER);
    expandAll(myTree);
  }

  public static void main(String args[]) {
    TestTree myTestTree = new TestTree();
    myTestTree.init();
    myTestTree.setVisible(true);
    
  }
  // to expend all nodes of a Tree
  public void expandAll(JTree tree) {
    int row = 0;
    while (row < tree.getRowCount()) {
      tree.expandRow(row);
      row++;
      }
    }
}

Output of the Progam

tree in data structure

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment