Sep 24, 2015

Recursive search in a non-binary tree in TreeView of JavaFX

Search for a node in a non-binary tree (any node can have multiple children 0-n) and exit from recursion immediately, when the first hit is found. We give an example with the search of a TreeItem with a given name in a TreeView of JavaFX, which can be easily adapted to any tree like structure:

TreeItem<String> searchTreeItem(TreeItem<String> item, String name) {
	if(item.getValue().equals(name)) return item; // hit!

	// continue on the children:
	TreeItem<String> result = null;
	for(TreeItem<String> child : item.getChildren()){
		 result = searchTreeItem(child, name);
		 if(result != null) return result; // hit!
	//no hit:
	return null;

If you want to search the whole tree treeView for a node with name "bigdev", just pass in the root:

TreeItem<String> result = searchTreeItem(treeView.getRoot(), "bigdev");


  1. Great! We will be connecting to this enormous post on our site. Continue the good writing.