[C語言]鏈式二叉樹insert 和 find 操作

天道酬勤,每日記點筆記也是蠻有意思的。

插入函數(shù):

#include <assert.h>
#include <stdio.h>
#include <malloc.h>

typedef TREE_TYPE int;

typedef struct TREE_NODE{
  TREE_TYPE value;
  struct TREE_NODE *left;
  struct TREE_NODE *right;
}TreeNode;

static TreeNode *tree;

/*
  insert
*/
void insert(TREE_TYPE value){
  TreeNode *current; //point to the current node
  TreeNode **linked; //pointer pointing to another pointer

  linked = &tree;
  // as we know,left node is less than mid, and mid bigger than right
  // left < mid < right
  while( (current = *linked) != NULL ){
      if(current->value > value){
        linked = &current->left;
      }else{
        assert(value != current->value);
        linked = &current->right;
      }
  }
  /*
      now find which position to insert the node 
      because of the node is left ,means the end 
  */
  current = (TreeNode *)malloc(sizeof(TreeNode));
  assert(current != NULL);//guarantee The memory alloced never be NULL
  current->value = value;
  current->left =NULL;
  current->right = NULL;
  *linked = current;
}

find函數(shù)相對來說簡單一些:

TREE_TYPE *find(TREE_TYPE value)
{
  TreeNode *current;      //this time ,just use one simple pointer
  current = tree;

  // notice node and child relation : left < mid < right
  while(current != NULL && current->value != value){
      if(value < current->value)
            current = current->left
      else
            current = current->right
  }
  
  // not find
  if(current == NULL)  return NULL;

  return &current->value;  // return a pointer means you can change it!
}

前序(pre-order)遍歷,即先遍歷當前中間節(jié)點,后遍歷左節(jié)點和右節(jié)點。這里使用遞歸比較合適:

notice : pre-order / in-order / post-order / breadth-first

static void do_pre_order_traverse(TreeNode *current,void (*callback)(TREE_TYPE value)){
  if(current != NULL){
      callback(current->value);  //do something with mid item
      
      do_pre_order_traverse(current->left);//do something with left item
      do_pre_order_traverse(current->right);//do something with right item
  }
}
void pre_order_traverse(void (*callback)(TREE_TYPE value)){
  do_pre_order_traverse(tree,callback);
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容