题目:
代码:
#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; }
参考:二叉树遍历(c++) - 知乎 (zhihu.com)
标签:arr,遍历,TreeNode,二叉树,pi,数据结构,root From: https://www.cnblogs.com/sodamate/p/16813118.html