Currently reviewing how to construct a BST, and it seems like there are two "common" ways of constructing it. One way, like this example, simply puts everything inside a Node class and does all the operation within such Node class. Another way is to break it down to both Node and BST class, and construct the tree from there.
I can see the appeal for both, but what is the standard way of constructing s BST? or is it really just more of a personal preference?
2 Answers 2
There's no good reason to have a separate BST class. It doesn't have any properties that a Node doesn't also have. Any Node is also a BST.
Alternatively there is no good reason to have a Node class, just a BST class.
Whatever you call it, there's only one of it.
Comments
A binary tree (a binary search tree is a special case of a binary tree that satisfies a property known as binary search tree property at every node) is a recursive data structure. A binary tree is either
- nothing (represented as null), or
- a node with three (optionally four) things (a key, a left child and a right child).
The optional fourth part of a node can be a parent reference, which itself is a tree. This reference is useful in several useful tree operations like node deletion (and even traversal).
So, a binary tree can be sufficiently represented by a node and vice-versa and a separate BST or BinaryTree representation (for instance, as a 'class') is not needed since a binary tree can be seen as a reference to its "root" node.
Since balancing of a BST is critical for its performance, it's important to note that in practice (e.g. library code), red-black trees usually replace binary (search) trees.
With respect to this representation, a binary tree is no different from an n-ary tree.
There is no need to define a 'subtree' while defining a binary tree. A separate BST class is not needed because a Node is enough to represent an entire tree.
Nodeclass with 2 child of each node. This will be more easy to handle and onlyrootwill be there for tree.