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;
}
相关推荐
慕容魏3 分钟前
入门到入土,Java学习 day16(算法1)
java·学习·算法
认真的小羽❅5 分钟前
动态规划详解(二):从暴力递归到动态规划的完整优化之路
java·算法·动态规划
坚定学代码14 分钟前
PIMPL模式
c++
imgsq18 分钟前
已安装 MFC 仍提示“此项目需要 MFC 库”的解决方法 (MSB8041)
c++·mfc
Vacant Seat1 小时前
图论-实现Trie(前缀树)
java·开发语言·数据结构·图论
香菇滑稽之谈1 小时前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式
蜕变的土豆1 小时前
二、重学C++—C语言核心
c语言·c++
LiDAR点云1 小时前
Matlab中快速查找元素索引号
数据结构·算法·matlab
CYRUS_STUDIO1 小时前
安卓逆向魔改版 Base64 算法还原
android·算法·逆向
JKHaaa2 小时前
数据结构之线性表
数据结构