Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
treeNode * FindMin(treeNode * node) { if(node==NULL) { return NULL; } if (node->left) //if the left of current node exists { return FindMin(node->left); //return and go down left side of node tree } else return node; // if we've reached the end, return current node } |
Explanations
1) Original FindMin with parameter node of data 10 gets pushed onto the call stack.
2) is the node NULL? nope
3) does the node have a left ? Yes! Hence…
4) Let’s recursively call and go down the left side of the tree by using node->left as its parameter. We will return whatever we find down there.
5) Therefore, we push another FindMin function with parameter node->left onto the stack.
The node->left evaluates to node with data 5.
1) for function FindMin with parameter node of data 5, we evaluate if the node is NULL. nope
2) does the node have a left? yes! Hence…
3) Let’s recursively call another FindMin and go down the left side of the tree by using node->left as the parameter. We will return whatever we find down there. node->left evaluates to node with data 1.
4) We push FindMin function onto the call stack with node with 1.
1) In FindMin function with node data 1, node is not NULL.
2) FindMin with node data 1 block node data 1’s node->left points to NULL, hence we need to return this node of data 1.
This means that we’ve reached the far end of the left side of the balanced sorted binary tree. A sorted binary tree just means that it keeps its smallest items at the left most, and largest item on its rightmost. It does this by comparing its current node, and shifting all larger nodes to the right, and shifting all smaller nodes to its left.
3) FindMin with node data 1 block returns node with data 1’s address.
4) FindMin with node data 1 block pop this FindMin with parameter NULL
5) FindMin with node data 5 block return node with data 1.
6) FindMin with node data 5 block pop FindMin with node data 5.
7) FindMin with node data 10 block return node data 1. See 5)
8) FindMin with node data 10 block pop FindMin with node data 10.