Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is level of root node in a tree?

Some articles say level of a root node is 0 whereas some say it's 1.

From https://www.gatevidyalay.com/tree-data-structure-tree-terminology/

In a tree, each step from top to bottom is called as level of a tree. The level count starts with 0 and increments by 1 at each level or step.

Here level of root is 0

And in http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/

The important thing to remember is when talking about level, it starts from 1 and the level of the root is 1. We need to be careful about this when solving problems related to level.

So it says that level is 1

I can't understand which one is correct.

like image 327
Okokok Avatar asked Dec 03 '19 06:12

Okokok


1 Answers

They are just different definitions. It is more common to define the level of a node as the number of edges in a path from the root node, which entails that the level of the root node is 0; but if you wish to define it as the position in that path using 1-based indexing then it is not wrong to do so, just unusual.

There is similarly a disagreement between definitions of the natural numbers; most texts define that 0 is the first natural number, some say 1 is. In practice, this creates almost no problems because either the definition is stated before it is used, or you can work out from the context which definition is being used, or it's used in a context where it makes no difference.

For example, if I say that the level of a child node is one more than the level of its parent, then the choice of definition doesn't matter. Alternatively, if I say that a complete binary tree has 2^h nodes at level h, then you can determine I am counting from 0 instead of 1.

like image 117
kaya3 Avatar answered Oct 17 '22 08:10

kaya3