二叉樹的其他操作

二叉樹一個較實用的操作就是二叉樹的複製,而二叉樹的複製可以在後序遍歷基礎上實現。
代碼實現:

//二叉樹的複製操作
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;
}

可滿足性問題:是否存在一種變量的賦值,使得表達式的值爲真。如:(x1¬x2)(¬x1x3)¬x3 ,首先我們要計算括號裏面的值,然後在計算整個表達式的值,直到整個表達式只有一個值。其表達式可以用二叉樹來表示,結構如圖:
這裏寫圖片描述
因此我們可以用二叉樹的後序遍歷來實現這條表達式。
代碼實現:

//邏輯值類型
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;
      }
   }
}
發佈了119 篇原創文章 · 獲贊 10 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章