题解 | 二叉树遍历
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
struct treenode {
char data;
treenode* left;
treenode* right;
treenode(char c): data (c),left(NULL),right(NULL){}
};
// get the pre-order to build the tree
treenode * buildtree(string & s ,int& index) {
//isempty
if(index >=s.length()) return NULL;
char c=s[index];
index++;
//if this node is empty ,then it cant have the children ,just return NULL
if (c == '#') return NULL;
treenode *node =new treenode(c);
node ->left=buildtree(s, index);
node ->right=buildtree(s, index);
return node;
}
// in-order
void inorder (treenode *t){
if(t==NULL) return;
inorder(t->left);
cout << t->data <<" ";
inorder(t->right);
}
int main() {
// get the input tree first
int index =0;
string s ;
cin >> s;
treenode* t = buildtree(s, index);
inorder(t);
return 0;
}
// 64 位输出请用 printf("%lld")
思路很简单 只要把格式写对就能做出来
