Professional Documents
Culture Documents
Lecture 06_Binary Tree Operation (1)
Lecture 06_Binary Tree Operation (1)
Lecture 06_Binary Tree Operation (1)
Introduction to Data
Structures
:Binary Tree Operation
Khairul Bashar
School of Information Technology
York University, Toronto.
Tree Traversals
• Print (in order) everything before the root node, print the root node,
print everything after the root node
• Print left sub-tree in order -> 1, 2, 3, 4
• Print the root node -> 5
• Print the right sub-tree in order -> 6, 7, 8, 9
• How to print the sub-trees in order?
• Recursion!
Tree Traversals
• Recursive sub-problem
• Print left (sub) sub-tree in order, print (sub) tree root, print right
(sub) sub-tree
• Base problem
• When can you stop?
• What’s a trivial BST to print?
• One node?
Recursive Method: Tree Traversal
// a method within public class BinaryNode
• rootPtr.printTree()
• left.printTree()
Code Trace
• left.printTree()
• left == null
• System.out.println(key)
• right.printTree()
• left == null
• System.out.println(key) -> 2
• right == null
• System.out.println(key) -> 3
• right.printTree()
• left == null
• System.out.println(key) -> 4
• right == null
• System.out.println(key) -> 5
• right.printTree()
• rootPtr.printTree();
• node3.printTree();
• node1.printTree();
• System.out.println(1);
• node2.printTree();
• System.out.println(3);
• node4.printTree();
Traversing orders
• Cannot do non-recursively
• Definition of a binary tree is recursive
• Binary tree operations are all recursive
• Recursion
• High-level concept of the algorithm
• Trust recursion to execute the subproblems properly
Time Complexity of Recursive
algorithms
• Recurrence relations
• The time to do a problem of size n
• T(n)
• The time to do a problem of size n-1
• T(n-1)
• A multiplication
• 1
• T(n) = T(n-1) + 1 T(1) = 1
• T(n) = O(n)
Time for a Binary Tree Traversal
• Recurrence relation
• Number of recursive case -> n
• Time required in each recursive case -> constant
• Total time -> T(n) = n*1 = O(n)
Time for Recursive Binary Search
• T(n) = T(n/2) + C
• T(n/2) = T(n/4) + C + C
• T(n/4) = T(n/8) + C + C + C -> T(n/23) + 3C -> pattern?