码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-04 19:02:45      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 1 #include <cstdio>
 2 #include <cstdlib>
 3 
 4 typedef struct BTNode{
 5     int key;
 6     struct BTNode *lchild;
 7     struct BTNode *rchild;
 8 }BTNode;
 9 
10 BTNode *createBinaryTree(int a[], int n) {
11     BTNode *nodes[n];
12     for (int i = 0; i < n; ++i) {
13         nodes[i] = (BTNode *) malloc(sizeof(BTNode));
14         nodes[i]->key = a[i];
15         nodes[i]->lchild = NULL;
16         nodes[i]->rchild = NULL;
17     }
18 
19     for (int i = 0; i < n; ++i) {
20         char str[10];
21         scanf("%s", str);
22         if (str[0] == d) {
23             int left, right;
24             scanf("%d %d", &left, &right);
25             nodes[i]->lchild = nodes[left - 1];
26             nodes[i]->rchild = nodes[right - 1];
27         } else if (str[0] == l) {
28             int left;
29             scanf("%d", &left);
30             nodes[i]->lchild = nodes[left - 1];
31         } else if (str[0] == r) {
32             int right;
33             scanf("%d", &right);
34             nodes[i]->rchild = nodes[right - 1];
35         }
36     }
37 
38     return nodes[0];
39 }
40 
41 /*
42 void getTreeMirror(BTNode *root) {
43     if (!root)
44         return;
45     if (!root->lchild && !root->rchild)
46         return;
47 
48     BTNode *temp = root->lchild;
49     root->lchild = root->rchild;
50     root->rchild = temp;
51 
52     getTreeMirror(root->lchild);
53     getTreeMirror(root->rchild);
54 }*/
55 
56 void printTreeMirror(BTNode *root, int count) {
57     if (root) {
58         count == 0 ? printf("%d", root->key) : printf(" %d", root->key);
59         printTreeMirror(root->lchild, count + 1);
60         printTreeMirror(root->rchild, count + 1);
61     }
62 }
63 
64 int main() {
65     int n;
66     while (scanf("%d", &n) != EOF) {
67         int a[n];
68         for (int i = 0; i < n; i++)
69             scanf("%d", &a[i]);
70 
71         BTNode *root = createBinaryTree(a, n);
72         printTreeMirror(root, 0);
73         printf("\n");
74     }
75 
76     return 0;
77 }
78 /**************************************************************
79     Problem: 1521
80     User: tonyhu
81     Language: C++
82     Result: Runtime Error
83 ****************************************************************/

 

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

标签:

原文地址:http://www.cnblogs.com/tonyhu1993/p/4702674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!