Skip to content

Trees ~ An importanat data structure

Rahil khan edited this page Jun 7, 2022 · 1 revision

Trees

Introduction

From GeeksforGeeks

Similarly, the tree data structure is a kind of hierarchal data arranged in a tree-like structure. It consists of a central node, structural nodes, and sub-nodes, which are connected via edges. We can also say that tree data structure has roots, branches, and leaves connected with one another. A tree is non-linear and a hierarchical data structure consisting of a collection of nodes such that each node of the tree stores a value, a list of references to nodes (the “children”).

tree

You can read more about trees here

Creating a tree

Creating a tree is so simple, create a root with some initial data & then keep adding children using the add() method. Every add() method returns a newly created TreeNode . You can use this reference to add a child into it again using the add() method.

For example ,

var root = new Tree<>(new Person("GrandMax",98));
 
var jhon = root.add(new Person("Maxwell", 85)).add(new Person("Jhon",37));  
jhon.add(new Person("Alice",17));  
jhon.add(new Person("Tom",16));  

var steve = root.add(new Person("MadMax", 84)).add(new Person("Steve",40));  
steve.add(new Person("Pricne",19));  
steve.add(new Person("Hanry",18));

You can see the Person class implementation here

This will create a tree-like this,

image

Traversing a tree/iterating

Just like the graph, here also you don't need to write your own algorithms for traversing the tree. There are convenient methods for you.

For example,

To get all the children of a node

TreeNode<Person>[] children = root.children(); // [Maxwell,MadMax]
TreeNode<Person>[] children = jhon.children(); // [Tom,Alice]

To search for a child

Objects[] result = root.search(person -> person.name.contains("Max")); // [Maxwell,MadMax]
Objects[] result = root.search(person -> person.age > 80); // [ALL NODES]

Note: The search performed on any node, will find the results in the whole hierarchy starting from there.

Some extra method's

  • boolean contains = root.contains("Prince") will check if there is any data with id "Prince" in that perticular node.
  • boolean contains = root.isEmpty() if the node does not have any child.
  • root.remove("Tom") Delete's the node whose id is "Tom" from the current node.

That's all

That's all about the tree. Now you have mastered the tree data structure, Now if you don't have completed DSA yet, go for it. It will help you to create the best tree.