Lecture 32 - Nov 24, 2023
Last lecture
Inheritance.
Today
Binary trees.
Recall: We used linked lists to have a more dynamic and flexible data structure to store information.
However, the way a data structure is organized can “speed up” or “slow down” the run time of some operations like searching, inserting, and deleting nodes.
Trees
Trees
is another data structure that stores data for different purposes (e.g., to store directories/files in Unix)
Properties of trees
- Have nodes and edges connect nodes
- Have no cycles
- Have 1 parent, multiple children
- Have 1 root (or empty trees have no root)
This is a tree
A
/
B
This is not a tree (cycle)
A
/ \
B - C
Binary trees
- The root is at the top and leaves are at the bottom
- Each node stores some data
- Each node has at most 2 child nodes, and one parent (Except root)
- An edge links a node to its children
- Nodes with no children are leaf nodes
In binary search trees (BST), an additional feature is that for every node:
- All nodes in the left subtree have values less than the node’s value
- All nodes in the right subtree have values greater than the node’s value
Facts:
- The minimum value is in the most left node
- The maximum value is in the most right node
As opposed to linked lists and arrays, BST is organized in such a way that allows quick search.
Complexity cases
If BST
8
/
4
/
3
/
1
Height is \(n\). Then \(T(n) = O(n)\), like arrays or linked lists.
If BST
8
/ \
3 10
/ \ / \
1 4 9 11
Height is \(\log(n)\). Then \(T(n) = O(\log(n))\).
BST implementation
class BSTNode {
private:
int value;
*left, *right;
BSTNode
public:
(int v) { value = v; left = right = NULL; }
BSTNode~BSTnode() { delete left; delete right; }
int getValue() { return value; }
*getRight() { return left; }
BSTNode *getLeft() { return left; }
BSTNode void setRight(BSTNode *r) { right = r; }
void setLeft(BSTNode *l) { left = l; }
};
class BSTree {
private:
* root;
BSTNodebool searchNode(int v, BSTNode *n) {
if (n == NULL) {
return false;
} else if (n->getValue() == v) {
return true;
} else if (n->getValue() > v) {
return searchNode(v, n->getLeft());
} else {
return searchNode(v, n->getRight());
}
}
public:
() { root = NULL; }
BSTree~BSTree() { delete root; }
* getRoot() { return root; }
BSTNodebool search(int v) { return searchNode(v, root); }
// next lecture: print insert
}