给定一棵非空二叉树,其结点的数据域为不等于0的整数,请编写程序输出该二叉树中第k层最后一个结点的值,若不存在则输出0。
输入格式:
输入第1行为一组用空格间隔的整数,个数不超过100个,表示带空指针信息的二叉树先根序列。其中空指针信息用0表示。第2行为一个整数k。
输出格式:
输出为一个整数,表示该二叉树中第k层最后一个结点的值,若不存在则输出0。
输入样例1:
1 2 0 0 3 0 0
1
结尾无空行
输出样例1:
3
结尾无空行
输入样例2:
1 -2 0 0 3 -1 0 0 -1 0 0
2
结尾无空行
输出样例2:
-1
结尾无空行
作者
朱允刚
单位
吉林大学
代码长度限制
16 KB
时间限制
50 ms
内存限制
64 MB
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct TNode* Position;
typedef Position BinTree;
struct TNode {
int Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(BinTree BT) {
int val;
BinTree bt;
BT = (BinTree)malloc(sizeof(struct TNode));
BT->Left = BT->Right = NULL;
bt = BT;
scanf("%d", &val);
if (val == 0) {
return NULL;
}
bt->Data = val;
bt->Left = CreatBinTree(bt->Left);
bt->Right = CreatBinTree(bt->Right);
return bt;
}
int flag = 0;
void PreorderTraversal(BinTree BT, int Depth, int h) {
if (!BT)return;
else if (Depth == h) {
flag = 1;
printf("%d", BT->Data);
}
if (!flag) {
h++;
PreorderTraversal(BT->Right, Depth, h);
if(!flag)PreorderTraversal(BT->Left, Depth, h);
}
}
int main() {
int Depth;
BinTree BT = (BinTree)malloc(sizeof(struct TNode));
BT = CreatBinTree(BT);
scanf("%d", &Depth);
PreorderTraversal(BT, Depth, 0);
if (!flag)printf("0");
system("pause");
return 0;
}