Lecture11: Basic Data Structure with Binary Tree 5/29/2012

advertisement
Lecture11: Basic Data
Structure with Binary Tree
5/29/2012
Slides modified from Yin Lou, Cornell CS2022: Introduction to C
1
Administration
• Assignment #10 is on the course homepage and due 6/13.
2
A Binary Tree
• A tree is a data structure for fast search, insertion,
deletion, etc.
• Each element in the tree leads to two further
elements.
struct TreeNode {
int val;
struct TreeNode* leftChild;
struct TreeNode* rightChild;
};
typedef struct TreeNode TreeNode;
A Binary Tree
10
8
5
30
20
40
Why is search fast (also insertion and deletion)?
Binary Tree Data Structure
• A tree node includes:
– The data
– Pointers to two children nodes (left and right)
• 2 pointers == binary
• Left node pointer points to a node with data less than the
current node
– All nodes to the left contain data less
• Right node pointer points to a node with data greater than
the current node
• All nodes to the right contain data greater
• A leaf node is a node with no children
• A root node is the top node
Add a node (20) - now add 15
• Simply add a leaf to the tree.
– Add 20
10
8
5
10
30
8
40
5
30
20
40
Add a node (15) – now add 9
10
8
30
5
20
15
40
Add a node (9) – now add 25
10
8
5
30
9
20
15
40
Add a node (25)
10
8
5
30
9
20
15
40
25
How to implement addNode()?
• Think before Code!
• Think phase
– Understand the problem
– Draw a solution and how it works to solve the problem
• Coding phase
– Put your solution into code
TreeNode* newNode(int val) {
TreeNode* node = malloc(sizeof(TreeNode));
node->val = val;
node->leftChild = NULL;
node->rightChild = NULL;
return(node);
}
void addNode(TreeNode** node, int val) {
if (*node == NULL)
*node = newNode(val);
else if ((*node)->val > val)
addNode(&((*node)->leftChild), val);
else if ((*node)->val == val)
printf("Error: %d already exists\n", val);
else
addNode(&((*node)->rightChild), val);
}
How to implement printTree()?
• Again Think before Code!
• Designing phase
– Understand the problem
– Draw a solution and how it works to solve the problem
• Coding phase
– Put your solution into code
printTree()
void printTree(TreeNode* node) {
if (node == NULL)
return;
if (node->leftChild != NULL)
{
printTree(node->leftChild);
}
printf("%d ", node->val);
if (node->rightChild != NULL)
{
printTree(node->rightChild);
}
}
How to implement printTreeInReverse()?
• Again Think before Code!
• Designing phase
– Understand the problem
– Draw a solution and how it works to solve the problem
• Coding phase
– Put your solution into code
How to implement deleteNode()?
• Three possible cases to consider:
– Deleting a leaf (node with no children)
– Deleting a node with one child
– Deleting a node with two children
Assignment #9
• Code these functions
–
–
–
–
–
void printTreeInReverse(TreeNode* node);
TreeNode* findNode(TreeNode* node, int val);
TreeNode* findMinNode(TreeNode* node);
TreeNode* findMaxNode(TreeNode* node);
void deleteNode(TreeNode** node, int val); // not easy!
16
Download