[Jobdu] 题目1521:二叉树的镜像

不知道怎么回事下面的代码通过了4个测试用例,还有1个测试用例始终是Runtime Error,各位帮我看一下是哪里出了问题

镜像输出两种方法,一种是递归进行调整,另外一种就是直接在先序遍历的基础上进行改造,下面代码中实现的是第二种

 #include <cstdio>
#include <cstdlib> typedef struct BTNode{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode; BTNode *createBinaryTree(int a[], int n) {
BTNode *nodes[n];
for (int i = ; i < n; ++i) {
nodes[i] = (BTNode *) malloc(sizeof(BTNode));
nodes[i]->key = a[i];
nodes[i]->lchild = NULL;
nodes[i]->rchild = NULL;
} for (int i = ; i < n; ++i) {
char str[];
scanf("%s", str);
if (str[] == 'd') {
int left, right;
scanf("%d %d", &left, &right);
nodes[i]->lchild = nodes[left - ];
nodes[i]->rchild = nodes[right - ];
} else if (str[] == 'l') {
int left;
scanf("%d", &left);
nodes[i]->lchild = nodes[left - ];
} else if (str[] == 'r') {
int right;
scanf("%d", &right);
nodes[i]->rchild = nodes[right - ];
}
} return nodes[];
} /*
void getTreeMirror(BTNode *root) {
if (!root)
return;
if (!root->lchild && !root->rchild)
return; BTNode *temp = root->lchild;
root->lchild = root->rchild;
root->rchild = temp; getTreeMirror(root->lchild);
getTreeMirror(root->rchild);
}*/ void printTreeMirror(BTNode *root, int count) {
if (root) {
count == ? printf("%d", root->key) : printf(" %d", root->key);
printTreeMirror(root->lchild, count + );
printTreeMirror(root->rchild, count + );
}
} int main() {
int n;
while (scanf("%d", &n) != EOF) {
int a[n];
for (int i = ; i < n; i++)
scanf("%d", &a[i]); BTNode *root = createBinaryTree(a, n);
printTreeMirror(root, );
printf("\n");
} return ;
}
/**************************************************************
    Problem: 1521
    User: tonyhu
    Language: C++
    Result: Runtime Error
****************************************************************/
上一篇:Apple Watch PSD 源文件【免费素材下载】


下一篇:MySQL命令行查询乱码解决方法