What is level of root node in a tree?

我是研究僧i 提交于 2020-12-30 17:18:55

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/59151282/what-is-level-of-root-node-in-a-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!