算法与数据结构——二叉树遍历应用
题目:
代码:
#include <iostream> #include <stdlib.h> using namespace std; typedef struct TreeNode { char data; struct TreeNode* lchild; struct TreeNode* rchild; }TreeNode; //先序创建二叉树 TreeNode* CreateTree(char* arr,int *pi) { //arr->字符串 //pi->下标位置 if (arr[*pi] == '#') return NULL; else { TreeNode * root = (TreeNode *)malloc (sizeof(TreeNode)); root->data = arr[*pi]; ++(*pi); root->lchild = CreateTree(arr,pi); ++(*pi); root->rchild = CreateTree(arr,pi); return root; } } //中序遍历输出 void InOrderTraversal(TreeNode * root) { if (root == NULL) return ; InOrderTraversal(root->lchild); cout << root->data << " "; InOrderTraversal(root->rchild); } int main() { char arr[100]; cin >> arr; int i = 0; TreeNode * root = CreateTree(arr,&i); InOrderTraversal(root); return 0; }