求根结点到x结点的路径(假定结点不重复)。
输入样例:
输入一行字符序列先序递归构建二叉树。每个字符对应一个结点,#表示空结点。第二行输入一个结点值x。
52#3##41##6##
3
输出样例:
输出从根到结点x的路径。
5 2 3
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <bits/stdc++.h>
#define MAXSIZE 100
typedef struct TNode * BinTree; /* 二叉树类型 */
typedef char ElementType;
struct TNode{ /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};
BinTree CreatBinTree()
{
ElementType ch;
BinTree T;
scanf(" %c", &ch); /* 按先序次序输入树的结点,空树输入@ */
if (ch == '#')
T = NULL;
else {
T = (BinTree)malloc(sizeof(struct TNode));
T->Data = ch;
T->Left = CreatBinTree();
T->Right = CreatBinTree();
}
return T;
}
int PreorderTraversal(BinTree BT, ElementType n, ElementType *path, int index) {//找路径的关键代码。
if (BT == NULL) {
return -1;
}
path[index] = BT->Data;
if (BT->Data == n) {
return index+1;//返回该下标对应的值;
}
int leftIdx = PreorderTraversal(BT->Left, n, path, index+1);
if (leftIdx > 0) {
return leftIdx;
}
int rightIdx = PreorderTraversal(BT->Right, n, path, index+1);
if (rightIdx > 0) {
return rightIdx;
}
return -1;
}
int main() {
BinTree BT;
BT = CreatBinTree();
ElementType n;
scanf(" %c", &n);
ElementType path[MAXSIZE];
int index = 0;
int result = PreorderTraversal(BT, n, path, index);
if (result > 0) {
for (int i = 0; i < result; i++) {
printf("%c ", path[i]);
}
} else {
printf("Not found.");
}
return 0;
}