7-14 求根结点到x结点的路径

求根结点到x结点的路径(假定结点不重复)。

输入样例:

输入一行字符序列先序递归构建二叉树。每个字符对应一个结点,#表示空结点。第二行输入一个结点值x。

52#3##41##6##
3

输出样例:

输出从根到结点x的路径。

5 2 3 
#include 
#include 
#include 

using namespace std;

struct TreeNode {
    char val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(char c) : val(c), left(NULL), right(NULL) {}
};

TreeNode* buildTree(string& str, int& index) {
    if (index >= str.length() || str[index] == '#') {
        index++;
        return NULL;
    }
    TreeNode* root = new TreeNode(str[index]);
    index++;
    root->left = buildTree(str, index);
    root->right = buildTree(str, index);
    return root;
}

bool getPath(TreeNode* root, char x, vector& path) {
    if (root == NULL) {
        return false;
    }
    path.push_back(root);
    if (root->val == x) {
        return true;
    }
    if (getPath(root->left, x, path) || getPath(root->right, x, path)) {
        return true;
    }
    path.pop_back();
    return false;
}

int main() {
    string str;
    getline(cin, str);
    int index = 0;
    TreeNode* root = buildTree(str, index);

    char x;
    cin >> x;
    vector path;
    getPath(root, x, path);
    for (int i = 0; i < path.size(); i++) {
        cout << path[i]->val << " ";
    }
    cout << endl;

    string str2;
    cin.ignore();
    getline(cin, str2);
    index = 0;
    TreeNode* root2 = buildTree(str2, index);

    char x2;
    cin >> x2;
    vector path2;
    getPath(root2, x2, path2);
    for (int i = 0; i < path2.size(); i++) {
        cout << path2[i]->val << " ";
    }

    return 0;
}

 

你可能感兴趣的:(算法,数据结构,c++)