L3-016 二叉搜索树的结构 (30 分)

本文介绍了一种基于二叉搜索树的数据结构实现方法,并通过具体的例子展示了如何构建一棵二叉搜索树,包括插入节点、判断根节点、判断兄弟节点等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

L3-016 二叉搜索树的结构 (30 分)

二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。(摘自百度百科)

给定一系列互不相等的整数,将它们顺次插入一棵初始为空的二叉搜索树,然后对结果树的结构进行描述。你需要能判断给定的描述是否正确。例如将{ 2 4 1 3 0 }插入后,得到一棵二叉搜索树,则陈述句如“2是树的根”、“1和4是兄弟结点”、“3和0在同一层上”(指自顶向下的深度相同)、“2是4的双亲结点”、“3是4的左孩子”都是正确的;而“4是2的左孩子”、“1和3是兄弟结点”都是不正确的。

输入格式:

输入在第一行给出一个正整数N(≤100),随后一行给出N个互不相同的整数,数字间以空格分隔,要求将之顺次插入一棵初始为空的二叉搜索树。之后给出一个正整数M(≤100),随后M行,每行给出一句待判断的陈述句。陈述句有以下6种:

A is the root,即"A是树的根";
A and B are siblings,即"A和B是兄弟结点";
A is the parent of B,即"A是B的双亲结点";
A is the left child of B,即"A是B的左孩子";
A is the right child of B,即"A是B的右孩子";
A and B are on the same level,即"A和B在同一层上"。
题目保证所有给定的整数都在整型范围内。

输出格式:

对每句陈述,如果正确则输出Yes,否则输出No,每句占一行。

输入样例:

5
2 4 1 3 0
8
2 is the root
1 and 4 are siblings
3 and 0 are on the same level
2 is the parent of 4
3 is the left child of 4
1 is the right child of 2
4 and 0 are on the same level
100 is the right child of 3

输出样例:

Yes
Yes
Yes
Yes
Yes
No
No
No

代码
#include <bits/stdc++.h>
using namespace std;
struct BSTree
{
    int val;
    BSTree *left, *right;
    BSTree()
    {
        left = right = nullptr;
    }
    BSTree(int v)
    {
        val = v;
        left = right = nullptr;
    }
};

BSTree* insert(BSTree *root, int v)
{
    if(root == nullptr)
    {
        root = new BSTree(v);
    }
    else
    {
        if(root->val > v)
        {
            root->left = insert(root->left, v);
        }
        else
        {
            root->right = insert(root->right, v);
        }
    }
    return root;
}
int getHeight(BSTree *root, int v, int d)
{
    if( root == nullptr )
    {
        return d;
    }
    else
    {
        if(root->val > v)
        {
            return getHeight(root->left, v, d+1);
        }
        else if(root->val < v)
        {
            return getHeight(root->right, v, d+1);
        }
        else
            return d+1;
    }
}
int getHeight(BSTree *root, int v)
{
    return getHeight(root, v, 0);
}
BSTree* getFather(BSTree *father, BSTree *root, int v)
{
    if(root == nullptr)
    {
        return nullptr;
    }
    else
    {
        if(root->val > v)
        {
            return getFather(root, root->left, v);
        }
        else if(root->val < v)
        {
            return getFather(root, root->right, v);
        }
        else
        {
            return father;
        }
    }
}
BSTree* getFather(BSTree *root, int v)
{
    BSTree *father = nullptr;
    return getFather(father, root, v);
}
BSTree* getNode(BSTree *root, int v)
{
    if(root == nullptr)
        return root;
    else
    {
        if(root->val > v)
        {
            return getNode(root->left, v);
        }
        else if(root->val < v)
        {
            return getNode(root->right, v);
        }
        else
            return root;
    }
}
bool is_left_child(BSTree *root, int a, int b)
{
    BSTree *nb = getNode(root, b);
    BSTree *na = getNode(root, a);
    if(nb == nullptr || na == nullptr)
        return false;
    else if(nb->left == na)
        return true;
    else
        return false;
}
bool is_right_child(BSTree *root, int a, int b)
{
    BSTree *nb = getNode(root, b);
    BSTree *na = getNode(root, a);
    if(nb == nullptr || na == nullptr)
        return false;
    else if(nb->right == na)
        return true;
    else
        return false;
}
bool is_father(BSTree *root, int a, int b)
{
    BSTree *nb = getNode(root, b);
    BSTree *na = getNode(root, a);
    if(na == nullptr || nb == nullptr)
        return false;
    else if(na->left == nb || na->right == nb)
    {
        return true;
    }
    return false;
}
bool on_the_same_level(BSTree *root, int a, int b)
{
    BSTree *nb = getNode(root, b);
    BSTree *na = getNode(root, a);
    
    if(na == nullptr || nb == nullptr)
        return false;

    int aH = getHeight(root, a);
    int bH = getHeight(root, b);
    if(aH == bH && aH != 0 && bH != 0)
        return true;
    return false;
}
bool is_root(BSTree *root, int v)
{
    if(root == nullptr)
        return false;
    return root->val == v ? true:false;
}
bool is_siblings(BSTree *root, int a, int b)
{
    if(a == b)
        return false;
    BSTree *pa = getFather(root, a);
    BSTree *pb = getFather(root, b);
    if(pa == pb && pa != nullptr && pb != nullptr)
        return true;
    else
        return false;
}
vector<string> split(const string &str, const char &c)
{
    string buff = "";
    vector<string> vec;
    for(auto s: str)
    {
        if(s == c && buff != "")
        {
            vec.push_back(buff);
            buff = "";
        }
        else
            buff += s;
    }
    if(buff != "")
        vec.push_back(buff);
    return vec;
}
int main()
{
    int n;
    cin >> n;
    BSTree *root = nullptr;
    int t;
    for(int i=0;i<n;i++)
    {
        cin >> t;
        root = insert(root, t);
    }
    int k;
    cin >> k;
    string cmd;
    vector<string> tmp;
    bool flag;
    int a,b;
    for(int i=0;i<k;i++)
    {
        getline(cin, cmd);
        while(cmd == "")
            getline(cin, cmd);
        tmp = split(cmd, ' ');
        if(tmp[1] == "is")
        {
            if(tmp[3] == "root")
            {
                a = atoi(tmp[0].c_str());
                flag = is_root(root, a);
            }
            else if(tmp[3] == "parent")
            {
                a = atoi(tmp[0].c_str());
                b = atoi(tmp[5].c_str());
                flag = is_father(root, a, b);
            }
            else if(tmp[3] == "left")
            {
                a = atoi(tmp[0].c_str());
                b = atoi(tmp[6].c_str());
                flag = is_left_child(root, a, b);
            }
            else
            {
                a = atoi(tmp[0].c_str());
                b = atoi(tmp[6].c_str());
                flag = is_right_child(root, a, b);
            }
        }
        else
        {
            if(tmp[4] == "on")
            {
                a = atoi(tmp[0].c_str());
                b = atoi(tmp[2].c_str());
                flag = on_the_same_level(root, a, b);
            }
            else
            {
                a = atoi(tmp[0].c_str());
                b = atoi(tmp[2].c_str());
                flag = is_siblings(root, a, b);
            }
        }
        if(flag)
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
    }
    return 0;
}
### 关于二叉搜索树运行超时的解决方案 在处理二叉搜索树(BST)中的第 \(k\) 小元素查询时,可能会遇到性能瓶颈或运行超时的情况。这通常是因为递归调用栈过深或者数据规模过大导致的时间复杂度增加。以下是针对该问题的一些优化方法: #### 方法一:迭代法代替递归 递归虽然简洁易懂,但在大规模输入下可能导致堆栈溢出或时间消耗过多。可以改用显式的栈模拟中序遍历过程。 ```cpp class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> stk; TreeNode* curr = root; while (!stk.empty() || curr != nullptr) { while (curr != nullptr) { stk.push(curr); curr = curr->left; // 左子优先访问 } curr = stk.top(); // 取栈顶节点 stk.pop(); if (--k == 0) return curr->val; // 找到第 k 小的值 curr = curr->right; // 访问右子 } return -1; // 如果未找到返回默认值 } }; ``` 这种方法通过手动维护栈的方式避免了函数调用开销,从而提高了效率[^1]。 #### 方法二:提前终止遍历 如果只需要获取第 \(k\) 小的元素,则无需完成整个中序遍历。可以在发现目标后立即停止进一步操作。 上述代码片段已经实现了这一逻辑,在 `if (--k == 0)` 处即刻返回结果而不再继续探索剩余部。 #### 方法三:平衡化二叉搜索树 对于极端不平衡的 BST (如退化成链表),其高度接近线性增长,使得每次查找都需要 O(n) 时间代价。因此考虑构建自平衡版本的数据结构比如 AVL 或者红黑 来维持较低的高度 h≈log₂n ,进而降低单次检索所需的最大步数至 O(log n)[^1]。 然而实际编码过程中可能无法直接修改原始定义好的类属性,所以此策略更多适用于理论析阶段而非即时修复手段。 --- ### 总结 综上所述,可以通过采用非递归形式执行中序遍历以及适时结束程序两种方式有效缓解因频繁调用造成的延迟现象;另外长期来看调整基础架构向更加稳定的形态发展也是值得推荐的方向之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值