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. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

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

  3. Saegen Expert crosscut and miter saws function similar to round saws. There is a spherical saw blade powered by a powerful motor. In contrast to circular saws this is not fixed on the table. Instead, a person provides the work item down. The actual saw is actually mounted on an arm, which is slowly lowered over the combined, which cuts through the fabric.