Last active
December 17, 2015 10:18
-
-
Save pilky/5593296 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
struct rxt_enumerator_state { | |
rxt_node *node; | |
bool leftFinished; | |
bool rightFinished; | |
bool returned; | |
rxt_enumerator_state *previousState; | |
} | |
rxt_node *rxt_next_node(rxt_enumerator_state *state) { | |
//Get the node we want to print out | |
rxt_node *currentNode = state.node; | |
rxt_node *nextNode = NULL; | |
//If we haven't checked the left, set that as checked and use the left node as our next node | |
if (!state.leftFinished) { | |
state.leftFinished = true; | |
nextNode = currentNode.left; | |
//Same for if we haven't checked the right | |
} else if (!state.rightFinished) { | |
state.rightFinished = true; | |
nextNode = currentNode.right; | |
//If we've checked them both, set the current node to NULL | |
} else { | |
currentNode = NULL | |
} | |
//If the current node is set (i.e. it exists and we haven't checked both sides) then we | |
//Create the new state with our next node and assign that to our state pointer | |
if (currentNode) { | |
rxt_enumerator_state newState = {.node = nextNode, .previousState = state}; | |
rxt_enumerator_state currentState = state; | |
*state = newState; | |
//We may be at this state multiple times, but only want to return the node once | |
if (!currentState.returned) { | |
currentState.returned = true; | |
return currentNode; | |
//If we've been at the state before, continue execution until we reach the next node to return | |
} else { | |
return rxt_next_node(*state); | |
} | |
//If the node is NULL (i.e. we've reached beyond a leaf and/or checked both branches) | |
} else { | |
//If there is no previous state, we've reached the end of the tree | |
if (!state.previousState) return NULL; | |
//Jump back up to the previous state and then continue running until we reach a returnable node | |
*state = state.previousState; | |
return rxt_next_node(*state); | |
} | |
} | |
//You would call it like so | |
void doSomething { | |
rxt_enumerator_state state = {.node = myNode}; | |
while ((rxt_node *node = rxt_next_node(&state))) { | |
//Do something with node | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment