bluecode-满二叉搜索树查找

132 阅读2分钟

时间限制:C/C++ 1000MS,其他语言 2000MS
内存限制:C/C++ 256MB,其他语言 512MB
难度:简单
出题人:root

描述

给定2^n-1个不同的整数(1<=n<=10,n为整教),构建一棵平衡满二叉搜索树
二叉搜索树的定义如下:
1)节点的左子树只包含小于当前节点的数。
2)节点的右子树只包含大于当前节点的数。
3)所有左子树和右子树自身必须也是二叉搜索树。

输入描述

输入分2行
第一行为2^n-1个未排序的整数,空格分隔,用于构建二叉搜索树,其中1<=n<=10
第二行为待查找的整数.

输出描述

搜索的路径和结果.路径从根节点开始,用S表示,查找右树用R表示,查找左树使用L表示,找到后使用Y表示,最终未找到使用N表示.

用例输入 1 **

2 1 3 7 5 6 4
6

用例输出 1 **

SRY

用例输入 2 **

4 2 1 3 6 5 7
5

用例输出 2 **

SRLY

用例输入 3 **

1 2 3 4 5 6 7
8

用例输出 3 **

SRRN
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct TreeNode {
    int value;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int val) : value(val), left(nullptr), right(nullptr) {}
};

TreeNode* constructBSTHelper(vector<int>& nums, int start, int end) {
    if (start > end) return nullptr;
    int mid = start + (end - start) / 2;
    TreeNode* root = new TreeNode(nums[mid]);
    root->left = constructBSTHelper(nums, start, mid - 1);
    root->right = constructBSTHelper(nums, mid + 1, end);
    return root;
}

TreeNode* constructBST(vector<int>& nums) {
    if (nums.empty()) return nullptr;
    sort(nums.begin(), nums.end());
    return constructBSTHelper(nums, 0, nums.size() - 1);
}

string searchTree(TreeNode* root, int target) {
    string path = "S";
    TreeNode* current = root;
    while (current) {
        if (current->value == target) {
            return path + "Y";
        } else if (target < current->value) {
            if (current->left) {
                path += "L";
                current = current->left;
            } else {
                return path + "N";
            }
        } else {
            if (current->right) {
                path += "R";
                current = current->right;
            } else {
                return path + "N";
            }
        }
    }
    return path + "N";
}

int main() {
    string line;
    if (getline(cin, line)) {
        vector<int> nums;
        size_t pos = 0;
        while ((pos = line.find(' ')) != string::npos) {
            nums.push_back(stoi(line.substr(0, pos)));
            line.erase(0, pos + 1);
        }
        if (!line.empty()) {
            nums.push_back(stoi(line));
        }
        int target;
        if (cin >> target) {
            TreeNode* root = constructBST(nums);
            cout << searchTree(root, target) << endl;
        }
    }
    return 0;
}