To count leaves without recursion, use the concept of an iterator, for example, using STL for the RB tree underlying std::set and std::map ... Create a begin() and end() function for you tree that defines the first ordinal and the last node (in this case, the left-most node, and then the right-most node). Then create a function called
BinarySearchTreeNode* increment(const BinarySearchTreeNode* current_node)
that for a given current_node will return a pointer to the next node in the tree. Remember that to complete this implementation, you will need an extra parent pointer in your node type to help with the iteration process.
Your algorithm for increment() will look something like this:
- Check if there is a correct child for the current node.
- If there is a right child, use the while loop to find the leftmost node of this right subtree. This will be the "next" node. Otherwise, go to step # 3.
- If there is no child right in the current node, then check if the current node is the left-descendant of its parent node.
- If step # 3 is true, then the βnextβ node is the parent node, so you can stop at this stage, otherwise go to the next step.
- If step # 3 was false, then the current node is the right parent of the parent. Thus, you will need to move on to the next parent node using a while loop until you meet a node, which is the left-descendant of the parent node. The parent of this left-child node will then be the "next" node, and you can stop.
- Finally, if step # 5 takes you back to the root, then the current node is the last node in the tree, and the iterator will reach the end of the tree.
Finally, you will need the bool leaf(const BinarySearchTreeNode* current_node) function bool leaf(const BinarySearchTreeNode* current_node) , which will check if the given node is a node leaf. Thus, the counter function can simply iterate over the tree and find all leaf nodes, returning the final count after its completion.
If you want to measure the maximum depth of an unbalanced tree without recursion, you must track the depth at which the node was inserted in your tree insert() function. It may just be a variable in your node type, which is set when the node is inserted into the tree. Then you can iterate through three and find the maximum node leaf depth.
By the way, the complexity of this method, unfortunately, will be O (N) ... nowhere is as beautiful as O (log N).
source share