Domanda

Hi Im little confused with the difference between the depth and the diameter of a tree.Sorry if Its already asked but I couldn't find it.

È stato utile?

Soluzione

  • The depth of a node is the number of edges from the node to the tree's root node.
    A root node will have a depth of 0.

  • The height of a node is the number of edges on the longest path from the node to a leaf.
    A leaf node will have a height of 0.

  • The diameter (or width) of a tree is the number of nodes on the longest path between any two leaf nodes. The tree below has a diameter of 6 nodes.

A tree, with height and depth of each node


By the way, I've seen tree diameter (or width) been demonstrated in a very nice way: imagine your tree is a real object of buttons (or discs) and (equal length) strings. Pick any node/button and hold the tree by it in the air. The button that now hangs lowest is farthest away from the node you're holding. Now hold that lowest button and let go of the other. The button that now hangs lowest is is the node that is farthest away from the one you're holding. The diameter is the number of nodes between the one you're holding and the lowest one.

Altri suggerimenti

From crackinterviewtoday,

Diameter of a Tree is defined as the number of nodes on the longest path between two leaves in the tree.

But depth is the number of edges from the root node to the node.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top