What is the difference between tree depth and diameter?

前端 未结 2 1358
心在旅途
心在旅途 2021-01-28 09:03

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.

相关标签:
2条回答
  • 2021-01-28 09:46

    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.

    0 讨论(0)
  • 2021-01-28 09:50
    • 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.

    0 讨论(0)
提交回复
热议问题