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;
}
相关推荐
yi.Ist几秒前
关于若干基础的几何问题
c++·学习·算法·计算几何
毅炼19 分钟前
Netty 常见问题总结
java·网络·数据结构·算法·哈希算法
Anastasiozzzz22 分钟前
leetcodehot100--最小栈 MinStack
java·javascript·算法
历程里程碑30 分钟前
双指针2--盛水最多的容器
大数据·数据结构·算法·leetcode·elasticsearch·搜索引擎·散列表
hetao173383735 分钟前
2026-01-22~23 hetao1733837 的刷题笔记
c++·笔记·算法
风筝在晴天搁浅1 小时前
hot100 230.二叉搜索树中第K小的元素
数据结构·算法
curry____3031 小时前
数据结构学习笔记
数据结构·笔记·学习
宫瑾1 小时前
【C语言】嵌入式C加强学习
java·c语言·学习
June bug1 小时前
(#数组/链表操作)寻找两个正序数组的中位数
数据结构·python·算法·leetcode·面试·职场和发展·跳槽
通信小呆呆1 小时前
DDMA MIMO OFDM ISAC:从回波模型到距离-速度图与非相参积累的原理梳理
算法·信息与通信·ofdm·mimo·通信感知一体化