7-3 求根结点到x结点的路径

求根结点到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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹿林九

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值