二叉樹一個較實用的操作就是二叉樹的複製,而二叉樹的複製可以在後序遍歷基礎上實現。
代碼實現:
//二叉樹的複製操作
tree_pointer copy(tree_pointer original)
{
if(original)
{
tree_pointer temp=(tree_pointer)malloc(sizeof(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;
return temp;
}
return NULL;
}
另一個有用的操作是判斷兩顆二叉樹是否相等,其可以在前序遍歷的基礎上實現。
代碼實現:
//判斷兩顆二叉樹是否相等
int equal(tree_pointer fisrt,tree_pointer second)
{
if((!fisrt&&!second)||(fisrt&&second&&fisrt->data==second->data))
{
equal(fisrt->left_child,second->left_child);
equal(fisrt->right_child,second->right_child);
return TRUE;
}
return FALSE;
}
可滿足性問題:是否存在一種變量的賦值,使得表達式的值爲真。如:
因此我們可以用二叉樹的後序遍歷來實現這條表達式。
代碼實現:
//邏輯值類型
typedef enum {not_logical,and_logical,or_logical,true_logical,false_logical} logical;
typedef struct node *tree_pointer;
struct node
{
int value;//變量真假值賦值
logical data;//邏輯值
tree_pointer left_child,right_child;
};
void post_order_eval(tree_pointer node)
{
if(node)
{
post_order_eval(node->left_child);
post_order_eval(node->right_child);
switch(node->data)
{
case not_logical:
node->value=!node->right_child->value;
break;
case and_logical:
node->value=node->left_child&&node->right_child;
break;
case or_logical:
node->value=node->left_child||node->right_child;
break;
case true_logical:
node->value=true;
break;
case false_logical:
node->value=false;
break;
}
}
}