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;
}
相关推荐
闪电麦坤9515 分钟前
数据结构:树(Tree)
数据结构
DARLING Zero two♡18 分钟前
C++效率掌握之STL库:map && set底层剖析及迭代器万字详解
c++·stl·set·map
绯樱殇雪27 分钟前
编程题 02-线性结构3 Reversing Linked List【PAT】
c++·pat考试
Rachelhi1 小时前
C++.神经网络与深度学习(赶工版)(会二次修改)
c++·深度学习·神经网络
Inverse1621 小时前
C语言_自定义类型:结构体
c语言·开发语言·算法
Musennn1 小时前
102. 二叉树的层序遍历详解:队列操作与层级分组的核心逻辑
java·数据结构·算法·leetcode
越来越无动于衷1 小时前
java数组题(5)
java·算法
理论最高的吻1 小时前
77. 组合【 力扣(LeetCode) 】
c++·算法·leetcode·深度优先·剪枝·回溯法
学习中的码虫1 小时前
c 中的哈希表
数据结构·哈希算法·散列表
zyx没烦恼1 小时前
unordered_map和unordered的介绍和使用
开发语言·c++