Wednesday 18 March 2015

Tree Data Structure in Java | Tree Data Structure tutorials | Tree Data Structure tutorials with example | Tree Data Structure questions and answers |

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 it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment