Chapter 3 Tree
Preliminary
Terminology
Tree: collection of nodes
- a distinguishd node , called the root
- zero or more nonempty (sub)trees T~1~, T~2~, …, each of whose roots are connected by a directed edge from
N-node tree owns N-1 edges
Other terminologies
- Degree of a node: number of subtrees of the node
- Degree of a tree: maximum of degrees of nodes
- Parent
- Child
- Sibling
- Leaf: a node with degree 0
- Path from n~1~ to n~k~: (unique)
- Length of path: number of edges on the path
- Depth of n~i~: depth of root is 0
- Height of n~i~: height of leaves is 0
- Height / Depth of tree: height of root / depth of deepest leaf
- Ancestors of a node: including its parent node
- Descendants of a node
Implementation
-
List Representation
-
FirstChild-NextSibling Representaion
Tree{ |
it is not unique; but it can change any common tree to a binary tree
Binary Tree
Degree <= 2
typedef struct TreeNode *Tree; |
Expression Trees
[Eg1] Constructing an Expression Tree From Postfix Expression
[Solve] Stack
Tree Traversals
visit each node exactly once
T(N) = O(N)
Preorder Traversal
void Preorder(Tree tree){ |
Postorder Traversal
void Postorder(Tree tree){ |
Levelorder Traversal
void Levelorder(Tree tree){ |
Inorder Traversal
void Inorder(Tree tree){ |
void InorderIterative(Tree tree){ |
Preorder & Postorder traversals could be used in common trees but Inorder traversal could not
[Eg1] Directory listing in a hierarchical file index
[Eg2] Calculatiing the size of a directory
In Linux, we could
$ tree |
Threaded Binary Tree
there are N + 1 pointers to NULL wasted in common binary tree with N nodes
- Rule 1: if tree->left is NULL, replace it with a pointer to the inorder predocessor of tree
- Rule 2: if tree->right is NULL, replace it with a pointer to the inorder successor of tree
- Rule 3: Dummy-head node is needed, pointers of node ordered first or last in inorder traversal pointing to NULL should point to the dummy-head node
typedef struct ThreadedTreeNode *ThreadedTree; |
Complete Binary Tree
All leaf node are on 2 adjacent levels
The maxinum number of nodes on level :
The maxinum number of nodes in a binary tree of depth of :
The Search Tree ADT – BST
Defination
A Binary Tree
- Each key is an integer
- left < right
- right > left
Implementations
- Find
- FindMin
Tree FindMin(Tree root){ |
- FindMax
- Insert
Tree Insert(ElemType key, Tree root){ |
- delete
- Delete a leaf node: Reset its parent link to NULL
- Delete a degree 1 node: Replace the node by its single child
- Delete a degree 2 or more node:
- Replace the node by the largest onr in its left subtree / the smallest one in its right subtree
- Delete the replacing node from the subtree
Tree Delete(ElemType key, Tree root){ |