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;
}
相关推荐
PingdiGuo_guo20 分钟前
C++智能指针的知识!
开发语言·c++
Chuncheng's blog23 分钟前
CentOS 7如何编译安装升级gcc至7.5版本?
linux·运维·c++·centos
fail_to_code40 分钟前
递归法的递归函数何时需要返回值
算法
C137的本贾尼1 小时前
(每日一道算法题)二叉树剪枝
算法·机器学习·剪枝
吴声子夜歌1 小时前
OpenCV——Mat类及常用数据结构
数据结构·opencv·webpack
笑口常开xpr2 小时前
数 据 结 构 进 阶:哨 兵 位 的 头 结 点 如 何 简 化 链 表 操 作
数据结构·链表·哨兵位的头节点
BUG收容所所长2 小时前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
愚润求学2 小时前
【C++】类型转换
开发语言·c++
XRZaaa2 小时前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪3 小时前
数据结构测试模拟题(4)
数据结构·c++·算法