postorder 방식. 서브트리부터 만든 후 copy
tree_pointer copy(tree_pointer original) {
/* Returns a tree_pointer to an exact copy of the original tree */
tree_pointer temp;
if(original) {
temp = (tree_pointer)malloc(sizeof(struct node));
if(IS_FULL((temp)) {
fprintf(stderr, "The memory is full\\n");
exit(1);
}
temp->left_child = copy(original->left_child);
temp->right_child = copy(original->right_child);
temp->data = original->data; //postorder traversal
return temp;
}
return NULL;
}
preorder 방식. postorder 써도 되는데 preorder가 더 efficient
int equal(tree_pointer first, tree_pointer second) {
/* returns FALSE if the binary trees first and second are not equal,
otherwise returns TRUE */
return(
(!first && !second) || // both are NULL
(first && second && // both are NOT NULL
(first->data == second->data) && // preorder traversal
equal(first->left_child, second->left_child) &&
equal(first->right_child, second->right_child)))
}
void post_order_eval(tree_pointer node) {
/* modified postorder traversal to evaluate a propositional calculus tree */
if(node) {
post_order_eval(node->left_child);
post_order_eval(node->right_child);
switch(node->data) {
case not: node->value = !node->right_child->value;
break;
case and: node->value = node->right_child->value && node->left_child->value;
break;
case or: node->value = node->right_child->value || node->left_child->value;
break;
case T: node->value = TRUE;
break;
case F: node->value = FALSE;
}
}
}
leftmost node와 rightmost node는 dummy node를 가리킴
A의 indorder successor : A의 right_thread는 FALSE이므로 right child인 C로 감.
C의 left_thread는 FALSE이므로 left child인 F로 감.
F의 left_thread는 TRUE이므로 A의 successor는 F.
/* inorder successor를 찾는 함수 */
threaded_pointer insucc(threaded_pointer tree) {
/* find the inorder successor of a tree in a threaded binary tree */
threaded_pointer temp;
temp = tree->right_child;
if(!tree->right_thread)
while(!temp->left_thread)
temp = temp->left_child;
return temp;
}
/* 트리를 inorder 방식으로 순회하는 함수 */
void tinorder(threaded_pointer tree) {
/* traverse the threaded binary tree inorder */
threaded_pointer temp = tree;
for( ; ; ) {
temp = insucc(temp);
if(temp == tree) break; // 다시 돌아왔다는 건 전부 순회했다는 걸 의미
printf("%3c", temp->data);
}
}
void insert_right(threaded_pointer parent, threaded_pointer child) {
/* insert child as the right child of parent in a threaded binary tree */
threaded_pointer temp;
child->right_child = parent->right_child;
child->right_thread = parent->right_thread;
child->left_child = parent;
child->left_thread = TRUE;
parent->right_child = child;
parent->right_thread = FALSE;
/* 원래의 child가 현재의 child를 가리키게끔 만듦 */
if(!child->right_thread) { // when parent has a right child
temp = insucc(child); // find child’s successor: T
temp->left_child = child; // set T’s predecessor to child
}
}