题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
先序遍历字符串而不是二叉树的先序遍历
#include<iostream>
using namespace std;
struct TreeNode {
char data;
TreeNode* leftchild;
TreeNode* rightchild;
};
int index=0;
TreeNode* Preorder(string str) {
char c = str[index++];
if (c == '#') return NULL;
else {
TreeNode* p = new TreeNode; //申请一个新结点
p->data = c;
p->leftchild = Preorder(str);
p->rightchild = Preorder(str);
return p;
}
}
void inorder(TreeNode* t) {
if (t == NULL) {
return;
}
else{
inorder(t->leftchild);
cout << t->data << ' ';
inorder(t->rightchild);
return ;
}
}
int main() {
string str;
while (cin >> str) {
TreeNode *root = Preorder(str); //建树并且拿到初始结点
inorder(root);
}
}