Are empty Binary Search Trees valid?

前端 未结 7 1299
挽巷
挽巷 2021-01-12 12:48

I have two questions regarding binary search trees, both about empty trees.

  1. Is an empty tree (null) valid?
  2. Is a root node without children valid?
相关标签:
7条回答
  • 2021-01-12 13:37

    I think you're mixing together apples and oranges:

    1. null is a value in some programming languages, and it is related upon the concrete representation of your implementation of the data structure
    2. "Empty" is a property of the abstract data structure that we call "binary search tree"

    Now, a tree is an ordered set: nothing more, nothing less. A set can be empty, of course! This means that, in your implementation, something similar to:

    MyTree tree = null
    

    represent an empty tree? Well, it depends upon your model. You can think, for ex., that an empty subtree should be represented by a node without value and with the references to the leafs nullified: in that model, a null pointer is meaningless from a logical perspective. But this is only one approach! The sentinel-based approach is a joy to program with, but it's memory expansive: you can then model empty nodes with just null. In that case, a null pointer can be an empty tree.

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