Trees
Trees
D E F
Solutions
Iterative solution: Stack-based
Recursive solution
Binary tree case study 2:
breadth first values
Breadth first traversal (level-order
traversal)
of binary tree
A
Storing elements in an array list
A, B, C, D, E, F
D E F
Solution
Iterative solution:
Queue-based
Binary tree case study 3:
tree includes
A
Objective
Find a target node value in the tree
B C
This results in
D E F
True if value is found in tree
False, otherwise
Solution
Recursive traversal-based solution
Binary tree case study 4:
tree sum
Objective 3
Find total sum of values in binary tree
11 4
This results in 25
For tree given on right-hand side
4 2 1
Solution
Recursive traversal-based solution
Binary tree case study 5:
tree min
Objective 3
Find minimum value in binary tree
11 4
This results in 1
For tree given on right-hand side
4 2 1
Solution
Recursive traversal-based solution
Binary tree case study 6:
max path sum
Objective 3
Find maximum path sum
11 4
This results in 18
For tree given on right-hand side
4 2 1
Solution
Recursive traversal-based solution
Binary tree traversal
Processing all the nodes by
visiting each individual node exactly once
Pre-order (VLR)
Post-order (LRV) V
Algorithm PreOrder(T,v)
visit(v)
if T.hasLeft(v)
PreOrder(T, T.left(v))
if T.isRight(v)
PreOrder(T, T.Right(v))
Post-order traversal
In a post-order traversal
a node is visited after its left subtree
Algorithm PostOrder(T,v)
if T.hasLeft(v)
PostOrder(T,T.left(v))
if T.hasRight(v)
PostOrder(T,T.right(v))
visit(v)
In-order traversal
In an in-order traversal
a node is visited after its left subtree
Algorithm InOrder(T,v)
if T.hasLeft(v)
InOrder(T,T.left(v))
visit(v)
if T.hasRight(v)
InOrder(T,T.right(v))
Full binary tree
Full binary tree of height k
Binary tree of depth k having 2 k+1 -1 nodes
4 5 6 7
Complete binary tree
A complete binary tree of height k with n nodes
Its nodes corresponds to the nodes
1 1 1
2 3 2 3 2 3
4 5 6 7 4 5 4 5 7