二叉树的前序遍历是:根结点、左结点、右结点
假设我们要构造的二叉树是:前序遍历ABDCE,因程序中要知道叶子结点,扩展后为AB#D##C#E##
代码如下图所示:
#include <stdio.h> #include <stdlib.h> //二叉树的结构 typedef struct tree *BinTree; struct tree{ char data; BinTree left; BinTree right; }; //前序遍历递归构造二叉树 BinTree BuildBinTree() { char data; BinTree root; scanf("%c",&data); if (data == '#'){ root = NULL; } else { root = (BinTree)malloc(sizeof(struct tree)); root->data = data; root->left = BuildBinTree(); root->right = BuildBinTree(); } return root; } //前序遍历进行验证 void PreTraversalTree(BinTree root) { if (root != NULL) { printf("%c",root->data); PreTraversalTree(root->left); PreTraversalTree(root->right); } } int main() { BinTree root; printf("create Binary Tree "); root = BuildBinTree(); printf(" "); PreTraversalTree(root); system("pause"); return 0; }
输出结果: