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;
}
相关推荐
涛ing1 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
xrgs_shz2 小时前
MATLAB的数据类型和各类数据类型转化示例
开发语言·数据结构·matlab
独正己身2 小时前
代码随想录day4
数据结构·c++·算法
厂太_STAB_丝针3 小时前
【自学嵌入式(8)天气时钟:天气模块开发、主函数编写】
c语言·单片机·嵌入式硬件
我不是代码教父4 小时前
[原创](Modern C++)现代C++的关键性概念: 流格式化
c++·字符串格式化·流格式化·cout格式化
利刃大大5 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
charlie1145141915 小时前
从0开始使用面对对象C语言搭建一个基于OLED的图形显示框架(协议层封装)
c语言·驱动开发·单片机·学习·教程·oled
子燕若水5 小时前
mac 手工安装OpenSSL 3.4.0
c++
*TQK*5 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
Rachela_z5 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法