Documente Academic
Documente Profesional
Documente Cultură
• Trees
• Tree terminology
• Binary Search Trees
• Tree Traversal
a A tree
• Different types of trees :
- Rooted tree
- Ordered tree b c
- M-ary tree and binary tree
d e f g h
• Examples of trees:
- Directory tree
- Family tree
- Company organization chart
- Table of contents
- etc.
• Parent node :
- If b is a child of a, then a is the parent of b.
- All nodes except root have exactly one parent. a
• Subtree :
- any node of a tree, with all of its descendants.
b c
• Depth of a node :
- Depth of root node is 0.
- Depth of any other node is 1 greater than d e
depth of its parent.
• Height :
- Maximum of all depths.
• In a rooted tree, any node is the root of a subtree consisting of it and the
nodes below it.
• There is exactly one path between the root and each of the other nodes in
the tree
• Each node except the root has exactly one node above it in the tree, (i.e.
it’s parent), and we extend the family analogy talking of children,
siblings, or grandparents
a
left child right child
b c
Right subtree
Left subtree d e f g
h
Programming and Data Structures 8
Examples of Trees
• A free tree
• A binary tree
• A forest
class BTreeNode
{
int data = 0; data : 0
BTreeNode left = null;
BTreeNode right = null; left right
}
null null
• We may then build our binary tree using this node structure.
• Properties:
- Each value (key) in the tree exists at most once (i.e. no duplicates).
- The "greater-than" and "less-than" relations are well defined for the
data value.
12 John
5 16 James Joseph
4 7 13 21
Jack Jesus
2
• Base case:
if tree is empty, create new node for item
• Recursive case:
if key < root's value, add to the left subtree,
otherwise to the right subtree
• Postorder traversal:
- do postorder traversal of left subtree. b c
- do postorder traversal of right subtree.
- visit the node last and process.
- i.e. visits and processes each node in the tree AFTER d e
visiting and processing its children.
• Inorder traversal:
- do inorder traversal of left subtree.
- visit the node and process.
- do inorder traversal of right subtree.
- i.e. processes nodes in the tree in an ascending sorted order.
Programming and Data Structures 19
Example of Tree Traversal
12
5 16
4 7 13 21
Preorder:
Inorder:
Postorder:
a b 1 x y
Programming and Data Structures 23
Tree Examples : Binary Expression Trees
+ 1
* /
5 3 - 4
9 1