您的位置:首页 > 其它

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

2015-08-04 17:46 260 查看
不知道怎么回事下面的代码通过了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
;
for (int i = 0; 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 = 0; i < n; ++i) {
char str[10];
scanf("%s", str);
if (str[0] == 'd') {
int left, right;
scanf("%d %d", &left, &right);
nodes[i]->lchild = nodes[left - 1];
nodes[i]->rchild = nodes[right - 1];
} else if (str[0] == 'l') {
int left;
scanf("%d", &left);
nodes[i]->lchild = nodes[left - 1];
} else if (str[0] == 'r') {
int right;
scanf("%d", &right);
nodes[i]->rchild = nodes[right - 1];
}
}

return nodes[0];
}

/*
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 == 0 ? printf("%d", root->key) : printf(" %d", root->key);
printTreeMirror(root->lchild, count + 1);
printTreeMirror(root->rchild, count + 1);
}
}

int main() {
int n;
while (scanf("%d", &n) != EOF) {
int a
;
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);

BTNode *root = createBinaryTree(a, n);
printTreeMirror(root, 0);
printf("\n");
}

return 0;
}
/**************************************************************
Problem: 1521
User: tonyhu
Language: C++
Result: Runtime Error
****************************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: