-
-
Save jkoppel/4e3bae99ac6626b8f8adce323e5478b0 to your computer and use it in GitHub Desktop.
This file contains 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<stdio.h> | |
#include<stdlib.h> | |
#include<utility> | |
struct tree { | |
tree(int e, tree* l, tree *r) : element(e), left(l), right(r) {} | |
int element; | |
tree *left; | |
tree *right; | |
}; | |
enum DIR { LEFT_CHILD, RIGHT_CHILD }; | |
struct stack { | |
stack(DIR d, tree *v, stack *p) : dir(d), val(v), parent(p) {} | |
DIR dir; | |
tree *val; | |
stack *parent; | |
}; | |
std::pair<DIR, tree*> pop(stack*& s) { | |
auto res = std::make_pair(s->dir, s->val); | |
stack *tmp = s; | |
s = s->parent; | |
delete tmp; | |
return res; | |
} | |
void push(DIR dir, tree *t, stack*& s) { | |
s = new stack(dir, t, s); | |
} | |
void print_tree(tree *t) { | |
tree *cur = t; | |
stack *s = NULL; | |
begin_print_node: | |
if (cur == NULL) { | |
goto dispatch_stack_frame; | |
} else { | |
printf("("); | |
push(LEFT_CHILD, cur, s); | |
cur = cur->left; | |
goto begin_print_node; | |
} | |
print_element: | |
printf(" %d ", cur->element); | |
push(RIGHT_CHILD, cur, s); | |
cur = cur->right; | |
goto begin_print_node; | |
finish_print_node: | |
printf(")"); | |
goto dispatch_stack_frame; | |
dispatch_stack_frame: | |
std::pair<DIR, tree*> top_frame; | |
if (s == NULL) goto end; | |
top_frame = pop(s); | |
cur = top_frame.second; | |
if (top_frame.first == LEFT_CHILD) goto print_element; | |
else goto finish_print_node; | |
end: | |
return; | |
} | |
int main() { | |
tree *a = new tree(1, NULL, NULL); | |
tree *b = new tree(2, NULL, a); | |
tree *c = new tree(3, a, b); | |
print_tree(c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment