Lecture12 Handouts Proto
Lecture12 Handouts Proto
Lecture #12
• Binary Tree Traversals
• Evaluate Expressions Using
Pre/In/Post Traversals
2 7
Draw a dot next to each node as
3 4 8 you pass by its left side.
5 6 9
5 8
Draw a dot next to each node as
1 4 7 you pass by its right side.
2 3 6
The order you draw the dots is the
order of the post-order traversal!
Post-order:
ACEDBHIGF
Tree Traversal Challenge!
8
???
??? ???
These traversals all use recursion, and are nearly L.O.T. uses a
identical algorithms. breadth-first-search
to visit nodes.
10
O(n)
We initiate processing of the
node’s left subtree. PreOrder(cur->left);
PreOrder(cur-> right);
}
13
• Here’s a function that computes the value of an expression tree. We start by passing in a pointer to
the root of the tree.
• Step #1 is the base case. It checks for a number in a node, and if it finds one, just returns the value
of the number. All leaf nodes will be numbers.
• Steps #2 and #3 evaluate the left and right subtrees of the current node, and gets their values.
• Then step #4 applies the operator (e.g., * sign) to the two results, and returns the overall result.
• This should look familiar! It’s a post-order traversal in disguise. We process the left and right
subtrees first, and then finally process the current node (the operator).
(5+6)*(3-1)
1. If the current node is a ptr
number, return its value.
cur
2. Recursively evaluate the left
subtree and get the result.
3. Recursively evaluate the right cur
subtree and get the result.
4. Apply the operator in the
current node to the left and
right results; return the
result.
16
Expression Evaluation
Which other algorithm does this remind you of?
17
Binary Tree Challenge #1
18
struct Node {
int val;
Node *left, *right;
};
return sum;
} }
return sum;
sum += tree_sum(root->right);
sum += tree_sum(root->left);
int sum = root->value;
SEARCH
^
Binary Search Trees
What’s the big picture?
A binary search tree enables fast (log2N)
searches by ordering its data in a special way.
For every node j in the tree, all children to
j’s left must be less than it, and all children
to j’s right must be greater than it. e.g.,
Mae
Ebony Tina
• The tree to the right is a valid binary search tree. Let’s verify
this.
• Every value in Larry’s subtree is less than Larry. Every value in “Danny” “Jack” “Tom”
Larry’s right subtree is greater than Larry. NULL NULL NULL NULL NULL
• Every value in Fran’s subtree is less than Fran. Every value in
Fran’s right subtree is greater than Fran.
• Every value in Rhonda’s subtree is less than Rhonda (it’s
empty). Every value in Rhonda’s right subtree is greater than “Sam”
Rhonda.
NULL NULL
• The rest of the nodes are leaf nodes.
23
“Fran”
NULL “Fran” “Ronda” “Amy” “Nick”
NULL NULL NULL NULL NULL
“Danny”
NULL “Danny” “Nick” “Maddy”
NULL NULL NULL NULL NULL NULL
“Alex”
NULL NULL
right subtree.
• Invalid BST: Maddy is less than Manny but is in Manny’s
Larry!
• Invalid BST: Nick is in Larry’s left subtree, but Nick is >
• Valid BST
From left to right: •
24
“Dale”
NULL NULL
Randy: >Larry, <Ronda, not found
Dale: <Larry, <Fran, >Barry, ==Dale
27
Searching a BST
Here are two different BST search algorithms in C++,
one iterative and one recursive:
bool Search(int v, Node *root)
{
Node *ptr = root; bool Search(int v, Node *ptr)
while (ptr != nullptr) {
{ if (ptr == nullptr)
if (v == ptr->value) return false; // nope
return true; else if (v == ptr->value)
else if (v < ptr->value) return(true); // found!!!
ptr = ptr->left; else if (v < ptr->value)
else return Search(V,ptr->left);
ptr = ptr->right; else
} return Search(V,ptr->right);
return false; // nope }
}
28
pRoot true
ptr-> 13
true
7 17
bool Search(int V, Node *ptr) NULL
true
{
if (ptr == nullptr)
3 14 19
return(false); // nope NULL NULL NULL NULL NULL NULL
else if (V == ptr->value)
return(true); // found!!!
int main(void)
else if (V < ptr->value)
return(Search(V,ptr->left)); {
else bool bFnd;
return(Search(V,ptr->right)); bFnd = Search(14,pRoot);
} }
29
Right! N steps
Question:
If there are 4 billion nodes in a BST, how
many steps will it take to perform a search? WOW!
Now that’s PIMP!
Just 32!
Inserting A New Value Into A BST
30
“Larry”
Where would we add Carly
and Kory to our tree?
“Fran” “Ronda”
NULL NULL
“Barry” “Khang”
NULL NULL NULL
“Dale”
NULL NULL
Inserting A New Value Into A BST
31
std::string value;
Node *left,*right;
};
Now the C++ Code!
33
void insert(const
std::string value;std::string &value)
{Node *left,*right;
}; …
}
private:
Node *m_root;
};
Now the C++ Code!
34
void insert(const std::string &value) If our tree is empty, allocate
{ Just as with a regular a new node and point the
binary tree, we use a node
if (m_root == nullptr) root pointer to it – then
{ m_root = struct
new Node(value);
to hold ourreturn;
items.} we’re done!
return;
}
}
else if (value > cur->value) void main(void)
{ {
if (cur->right != NULL)
cur = cur->right; BinarySearchTree bst;
else bst.insert(“Larry”);
{
cur->right = new Node(value); ...
return;
} bst.insert(“Phil”);
}
} }
}
• Answers:
• Random: The numbers will form a “bushy” wide binary tree.
• Ordered: The numbers will look like a linked list going either left
(ordered in descending order) or right (ordered in ascending order).
Answer: Yes! Let's see on the board!
Thinking time!
e.g., 1,2,3,4,5,6,7 vs 4,2,6,1,3,5,7
into a tree impact the tree's structure?
Does the order in which you insert values
Inserting A New Value Into A BST
36
37
Once we’ve found the right spot, we can insert our new
node in O(1) time.
Groovy Baby!
38
return(pRoot->value); return(pRoot->value);
} }
“Larry”
Question: What’s the big-
oh to find the minimum or
“Fran” “Ronda” maximum element?
NULL NULL
“Barry” “Phil”
NULL NULL NULL NULL
Answer: O(log2(N))
39
return(GetMin(pRoot->left)); return(GetMax(pRoot->right));
} }
“bill” “frank”
cur NULL NULL NULL NULL cur
void InOrder(Node *cur)
{ Big-oh Alert!
if (cur == nullptr) // if empty, return… Output:
return; the big-Oh of printing
So what’s
bill
all the items in the
InOrder(cur->left); tree?
// Process nodes in left sub-tree.
danny
cout << cur->value; // Process the current node. frank
Right! O(n) since we have to visit jane
InOrder(cur->right); // Process nodes in right sub-tree.
} and print all n items. waa
41