7-2 求根结点到x结点的路径 分数 15


c 复制代码
#include <iostream>
#include <queue>
#include <vector>
#include <string>
using namespace std;

typedef char BTDataType;
typedef struct BTNode
{
    BTDataType _data;
    BTNode* _left;
    BTNode* _right;
    BTNode(BTDataType data, BTNode* left = nullptr, BTNode* right = nullptr)
        : _data(data)
        , _left(left)
        , _right(right)
    {

    }
}BTNode;

BTNode* CreatBTree(string& str, size_t& i) 
{
    if (i >= str.size())
        return nullptr;
    if (str[i] == '#')
    {
        i++;
        return nullptr;
    }
    BTNode* root = new BTNode(str[i++]);
    root->_left = CreatBTree(str, i);
    root->_right = CreatBTree(str, i);
    return root;
}

bool GetPath(BTNode* root, BTDataType x, vector<BTNode*>& path)
{
    //当前结点不空就记录 因为一定会路过
    if (root == NULL) 
        return false;
    path.push_back(root);

    if (root->_data == x)
        return true;

    //当前结点的左右子树都没有找到 则x定不路过当前结点 尾删当前结点
    if (!GetPath(root->_left, x, path) && !GetPath(root->_right, x, path))
    {
        path.pop_back();
        return false;
    }
    else
        return true;
}

int main() 
{
    string str;
    getline(cin, str);

    //建树
    size_t index = 0;
    BTNode* root = CreatBTree(str, index);

    BTDataType x = 0;
    cin >> x;

    //找路
    vector<BTNode*> path;
    GetPath(root, x, path);

    for(auto& e: path)
        cout << e->_data << " ";
    cout << endl;

    return 0;
}
相关推荐
GuWenyue1 小时前
传统Agent工具两大痛点!300行代码落地MCP跨语言工具,彻底解耦LLM与工具
前端·人工智能·算法
同勉共进2 小时前
记一例 vibe coding + gcc bug 导致的线程池死锁问题
c++·线程池·gcc·死锁·vibe coding
我叫洋洋2 小时前
C ++ [ hello world ]
c语言·c++·算法
天空'之城3 小时前
C 语言工业级通用组件手写 09:CRC32 数据校验
c语言·嵌入式开发·数据校验·crc32·工业级组件
奋发向前wcx3 小时前
y1,y2总复习笔记5 2026.7.19
数据结构·笔记·算法
王维同学6 小时前
[自学][Windows C++]RunOnceEx 注册表分组键的安全遍历
c++·windows·安全·开源
战族狼魂7 小时前
高频面试题精选:分治与AI Agent架构
人工智能·算法·大模型·大语言模型
李剑一7 小时前
你用过网易的将军令嘛?它底层实现账号保护的原理相当简单粗暴
算法
Scott9999HH7 小时前
告别流量波动玄学!从法拉第电磁定律到底层 C/C++ 流量累积算法,深度解密工业级电磁流量计选型与开发
c语言·c++·算法
中达瑞和-高光谱·多光谱7 小时前
1nm到8nm光谱分辨率,你的应用该选哪款光谱相机?
算法·高光谱·高光谱相机