What is the definition for the height of a tree?

前端 未结 7 450
南旧
南旧 2020-12-09 16:43

I can\'t seem to find a definitive answer for this, I\'m trying to do some elementary proofs on heaps but here\'s what\'s throwing me off a little bit:

Is an empt

相关标签:
7条回答
  • 2020-12-09 17:25

    Height of a tree is the length of the path from root of that tree to its farthest node (i.e. leaf node farthest from the root).

    A tree with only root node has height 0 and a tree with zero nodes would be considered as empty. An empty tree has height of -1. Please check this.

    I hope this helps.

    0 讨论(0)
  • 2020-12-09 17:33

    According to Wikipedia, the height of a (sub-)tree with one single node is 0. The height of a tree with no nodes would be -1. But I think it's up to you, how you define the height and your proofs should work with either definition.

    0 讨论(0)
  • 2020-12-09 17:38

    I think you should take a look at the Dictionary of Algorithms and Data Structures at the NIST website. There definition for height says a single node is height 0.

    The definition of a valid tree does include an empty structure. The site doesn't mention the height of such a tree, but based on the definition of the height, it should also be 0.

    0 讨论(0)
  • 2020-12-09 17:39

    I have seen it used in both ways (counting a single node as 0 or 1), but the majority of sources would define a root-only tree as a tree of height 0, and would not consider a 0-node tree valid.

    0 讨论(0)
  • 2020-12-09 17:39

    The height of a tree is the length of the longest path to a terminal node in either of its children.

    Wikipedia says the height of an empty tree is -1. I disagree. An empty tree is literally just a tree containing one terminal node (a null or special value which represents an empty tree). Since the node has no children, the length of its longest path must be the empty sum = 0, not -1.

    Likewise, a non-empty tree has two children, so by definition there is at least a path >= 1 to a terminal node.

    We might define our tree as follows:

    type 'a tree =
        | Node of 'a tree * 'a * 'a tree
        | Nil
    
    let rec height = function
        | Node(left, x, right) -> 1 + max (height left) (height right)
        | Nil -> 0
    
    0 讨论(0)
  • 2020-12-09 17:40

    If your tree is a recursively defined data structure which may be either empty or a node with a left and right subtree (for example search trees, or your heap), then the natural definition is to assign 0 to the empty tree and 1 + the height of the highest subtree to a nonempty tree.

    If your tree is a graph then the natural definition is the longest path from the root to a leaf, so a root-only tree has depth 0. You normally wouldn't even consider empty trees in this case.

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