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

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

输入样例:

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

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

输出样例:

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

5 2 3 
#include <iostream>
#include <vector>
#include <string>

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<TreeNode*>& 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<TreeNode*> 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<TreeNode*> path2;
    getPath(root2, x2, path2);
    for (int i = 0; i < path2.size(); i++) {
        cout << path2[i]->val << " ";
    }

    return 0;
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
求根节点到 x 结点路径可以通过递归法来实现。递归函数的思路是,如果当前根结点是 x 结点,那么路径就是根结点本身。否则,递归搜索当前根结点的左子树和右子树,如果找到 x 结点,则将根结点加入路径,并返回该路径。 具体实现如下: 1. 如果根结点为 x 结点,返回只包含根结点的列表。 2. 在左子树中递归搜索 x 结点,找到路径后,将根结点加入路径,并返回该路径。 3. 在右子树中递归搜索 x 结点,找到路径后,将根结点加入路径,并返回该路径。 4. 如果左子树和右子树都没有找到 x 结点,则返回空列表。 以下是使用递归法求根结点到 x 结点路径的示例代码: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def findPath(root, x): if root.val == x: return [root.val] elif root.left: left_path = findPath(root.left, x) if left_path: return [root.val] + left_path elif root.right: right_path = findPath(root.right, x) if right_path: return [root.val] + right_path return [] ``` 上述代码定义了一个树节点类 `TreeNode`,以及一个名为 `findPath` 的递归函数。使用该函数可以求得根结点到 x 结点路径。为了测试函数的正确性,我们可以创建一个二叉树,并调用 `findPath` 函数获取根结点到 x 结点路径。 希望以上内容能对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值