二叉树的前序、中序、后序遍历

小鱼儿 2022-06-11 02:36 327阅读 0赞
  • 二叉树的结构体

    typedef struct binaryTree {

    1. char item;
    2. struct binaryTree *lChild;
    3. struct binaryTree *rChild;

    }binaryTree, *pBinaryTree;

  • 二叉树的初始化创建,二叉树创建的过程中按照先序遍历的方式输入一颗满二叉树,缺失的节点元素使用#补足;构建的过程中先递归创建左子树,然后递归创建右子数;’#’作为递归的结束;

    pBinaryTree createBinaryTree() {

    1. char tmp = '0';
    2. pBinaryTree treeNode = NULL;
    3. scanf("%c", &tmp);
    4. if (tmp == '#')
    5. {
    6. treeNode = NULL;
    7. }
    8. else
    9. {
    10. //为加入的节点分配新的内存空间
    11. treeNode = (binaryTree*)malloc(sizeof(binaryTree));
    12. treeNode->item = tmp;
    13. //递归调用产生二叉树
    14. treeNode->lChild = createBinaryTree();
    15. treeNode->rChild = createBinaryTree();
    16. }
    17. return treeNode;

    }

  • 先序遍历二叉树

    void preVisitBiTree(pBinaryTree root) {

    1. if (root)
    2. {
    3. //先遍历根节点
    4. printf("%c", root->item);
    5. //遍历左子树
    6. preVisitBiTree(root->lChild);
    7. //遍历右子树
    8. preVisitBiTree(root->rChild);
    9. }

    }

  • 中序遍历二叉树

    void inVisitBiTree(pBinaryTree inRoot) {

    1. if (inRoot)
    2. {
    3. //先遍历左子树
    4. inVisitBiTree(inRoot -> lChild );
    5. //遍历根节点
    6. printf("%c", inRoot->item);
    7. //遍历右子树
    8. inVisitBiTree(inRoot->rChild);
    9. }

    }

  • 后序遍历二叉树

    void lastVisitBiTree(pBinaryTree lastRoot) {

    1. if (lastRoot)
    2. {
    3. //遍历左子树
    4. inVisitBiTree(lastRoot->lChild);
    5. //遍历右子树
    6. inVisitBiTree(lastRoot->rChild);
    7. //遍历根节点
    8. printf("%c", lastRoot->item);
    9. }

    }

三种遍历二叉树的递归结构是相似的,只是递归遍历的先后有区别

测试:

  1. int main() {
  2. //构建一颗二叉树
  3. pBinaryTree binaryTree = createBinaryTree();
  4. //采用先序遍历的方式遍历输出二叉树
  5. preVisitBiTree(binaryTree);
  6. printf("\n");
  7. //采用中序遍历的方式输出二叉树
  8. inVisitBiTree(binaryTree);
  9. printf("\n");
  10. lastVisitBiTree(binaryTree);
  11. printf("测试二叉树");
  12. return 0;
  13. }

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读