二叉树的创建与遍历

xiaoxiao2021-02-28  71

1.二叉树创建

//创建二叉树, 先序顺序 int CreateBiTree(pBiTree *root) { char ch = 0; fflush(stdin); if ((ch = getchar()) == 'a')//控制树的结构 { *root = NULL; } else { *root = (BiTNode *)malloc(sizeof(BiTNode)); if (!(*root)) { return RET_ERROR; } (*root)->data = GetRandom(); CreateBiTree(&(*root)->leftChild); CreateBiTree(&(*root)->rightChild); } return RET_OK; }

2.二叉树的遍历

先序遍历(根结点->左子树->右子树)

中序遍历(左子树->根结点->右子树)

后序遍历(左子树->右子树->根结点)

int PreOrderVisitTree(pBiTree T, VisitType pFuncVisit) { if (T) { (*pFuncVisit)(T->data); if (PreOrderVisitTree(T->leftChild, pFuncVisit) == RET_OK) { if (PreOrderVisitTree(T->rightChild, pFuncVisit) == RET_OK) { return RET_OK; } } return RET_ERROR; } else { return RET_OK; } }

转载请注明原文地址: https://www.6miu.com/read-26113.html

最新回复(0)