Data Structures-Trees
Data Structures-Trees
Data Structures-Trees
Carrano
Figure 10-2 Figure 10-1 A general tree A subtree of the tree in Figure 10-1
General tree
A general tree T is a set of one or more nodes such that T is partitioned into disjoint subsets:
A single node r, the root Sets that are general trees, called subtrees of r
Parent of node n
Child of node n
Root
Subtree of node n
Leaf
Siblings
Ancestor of node n
Descendant of node n
A binary tree that has the following properties for each node n
ns value is > all values in ns left subtree TL ns value is < all values in ns right subtree TR Both TL and TR are binary search trees
Height of a tree
Number of nodes along the longest path from the root to a leaf
Height 3 Height 5 Height 7
Figure 10-6 Binary trees with the same nodes but different heights
Recursive definition
If T is empty, T is a full binary tree of height 0 If T is not empty and has height h > 0, T is a full binary tree if its roots subtrees are both full binary trees of height h 1
All nodes at levels <= h 2 have two children each, and When a node at level h 1 has children, all nodes to its left at the same level have two children each, and When a node at level h 1 has one child, it is a left child
A binary tree is balanced if the heights of any nodes two subtrees differ by no more than 1 Complete binary trees are balanced Full binary trees are complete and balanced
The balance factor of a binary tree is the difference in height between it left and right sub-trees. Let :
height of left sub-tree be HL and height of right sub-tree be HR Then the Balance factor (B) = HL -HR
A full binary tree of height h 0 has 2h 1 nodes The maximum number of nodes that a binary tree of height h can have is 2h 1 The minimum height of a binary tree with n nodes is log2(n+1) Complete trees and full trees have minimum height The maximum height of a binary tree with n nodes is n
In the following recursive definition of the maximum number of nodes based on the height of a binary tree. Replace the question mark with the proper value.
Some array-based representations for binary trees exists. can you think of any?
Tree traversal requires that each node of the tree gets examined (processed or visit) once in a pre-defined sequence. Two general approaches are:
Process all the descendents of a child before going to the next child. There are three tasks that are performed when traversing:
Inorder (node* root) if(root != NULL) Inorder (root->left) visit(root->data) Inorder (root->right)
Postorder (node* root) if(root != NULL) Postorder (root->left) Postorder (root->right) visit(root->data)
Visit each node level by level What data structure can be used?
Level-order (node* root) queue Q Enqueue(root) while( Q is not empty) enqueue(children of root) dequeue(head) visit(head->data)