题解 | 二叉树遍历
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <stdio.h>
struct TreeNode {
char data;
TreeNode* left;
TreeNode* right;
};
TreeNode* RecursiveBuildTree(int &index, char str[]) {
char c = str[index];
index++;
if (c == '#') {
return NULL;
} else {
TreeNode* pNew = new TreeNode();
pNew->data = c;
pNew->left = RecursiveBuildTree(index, str);
pNew->right = RecursiveBuildTree(index, str);
return pNew;
}
}
void InOrder(TreeNode* root) {
if (root == NULL) {
return;
}
InOrder(root->left);
printf("%c ", root->data);
InOrder(root->right);
}
int main() {
char str[100];
while (scanf("%s", str) != EOF) {
int index = 0;
TreeNode* root = RecursiveBuildTree(index, str);
InOrder(root);
printf("\n");
}
}
查看24道真题和解析