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;
}
相关推荐
如竟没有火炬几秒前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
Greedy Alg3 分钟前
LeetCode 236. 二叉树的最近公共祖先
算法
R-G-B5 分钟前
【18】C实战篇——C语言 文件读写【fputc、fgetc、fputs、fgets】
c语言·c语言文件读写·fputc·fgetc·fputs·fgets
Maple_land16 分钟前
Linux进程第八讲——进程状态全景解析(二):从阻塞到消亡的完整生命周期
linux·运维·服务器·c++·centos
爱吃生蚝的于勒21 分钟前
【Linux】零基础学会Linux之权限
linux·运维·服务器·数据结构·git·算法·github
ajassi200030 分钟前
开源 C++ QT QML 开发(十一)通讯--TCP服务器端
c++·qt·开源
lyp90h30 分钟前
高效SQLite操作:基于C++模板元编程的自动化封装
c++
minji...1 小时前
Linux相关工具vim/gcc/g++/gdb/cgdb的使用详解
linux·运维·服务器·c++·git·自动化·vim
兮山与1 小时前
算法3.0
算法
_OP_CHEN1 小时前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现