【算法】二叉树输出根节点到某结点的路径

分析(递归):

  1. 空树,则查找失败,返回 false
  2. 当前结点为所要查找的值,输出结果,返回 true
  3. 以上条件不满足,则向左找或向右找,找着了说明当前结点是根到x路径上的点,输出并返回 true
  4. 左右都找不到,查找失败,无此结点,返回 false
bool printPath(node* root, int x) {
    if (root == NULL) return false;
    if (root->data == x) {
        printf("%d ", x);
        return true;
    }
    if (printPath(root->left, x) || printPath(root->right, x)) {
        printf("%d ", root->data);
        return true;
    }
    return false;
}

完整实现:

#include <bits/stdc++.h>
using namespace std;
struct node {
    int data;
    node *left, *right;
    node(int x) : data(x) { left = right = NULL; }
};
int pre[] = {1, 4, 3, 5, 8, 9, 2, 6, 7}, in[] = {3, 4, 8, 5, 9, 1, 6, 2, 7};
node* create(int prel, int prer, int inl, int inr) {
    if (prel > prer) return NULL;
    node* root = new node(pre[prel]);
    int k = inl;
    while (in[k] != pre[prel]) k++;
    int numleft = k - inl;
    root->left = create(prel + 1, prel + numleft, inl, k - 1);
    root->right = create(prel + numleft + 1, prer, k + 1, inr);
    return root;
}
// 输出从根节点到x的路径
bool printPath(node* root, int x) {
    if (root == NULL) return false;
    if (root->data == x) {
        printf("%d ", x);
        return true;
    }
    if (printPath(root->left, x) || printPath(root->right, x)) {
        printf("%d ", root->data);
        return true;
    }
    return false;
}
int main() {
    int n = 9;
    // for (int i = 0; i < n; i++) scanf("%d", pre + i);
    // for (int i = 0; i < n; i++) scanf("%d", in + i);
    node* root = create(0, n - 1, 0, n - 1);
    printPath(root, 8);
    return 0;
}

输出结果:

8 5 4 1
  • 1
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值