Trees
Trees
Topics covered
Trees
Definitions and terminology
Binary trees
Definitions and property
B C
D E
F G H
A
Terminology B C
In this tree D E
F G H
A is the root node
Subtree rooted at C
B is the parent of D and E
C is the sibling of B
D and E are the children of B
D, E, F, G, and H are leaves (or external nodes)
A, B, and C are internal nodes
Binary Tree B C
D E F G
Properties
Every node has at most two children
Denoted by left and right children
Subtree rooted at left child => left subtree
Subtree rooted at right child => right subtree
Level 0 Depth = 0
A
Level 1 Depth = 1 C
B
Level 2 F G
D E Depth = 2
Height of a node/tree
Height of a node
If it is external, then height = 0
Otherwise, height = 1 + height of max height of children
B Height of C = 1 C
D E Height of F = 0 F G
Binary tree representation
BTNode A element
left right
B C
D E F
BTNode<T> class
T element
BTNode<T> left
BTNode<T> right
Binary tree case study 1:
depth first values A
Depth first traversal
of binary tree
B C
Storing elements in an array list
Solutions
Iterative solution: Stack-based
Recursive solution
Binary tree case study 2:
breadth first values
Breadth first traversal (level-order A
traversal)
of binary tree
B C
Storing elements in an array list
Solution
Iterative solution:
Queue-based
Binary tree case study 3:
tree includes
Objective A
Find a target node value in the tree
B C
This results in
True if value is found in tree
D E F
False, otherwise
Solution
Recursive traversal-based solution