PAT甲级 1099 Build A Binary Search Tree (30分) 节点表示二叉树 层序遍历 中序遍历 柳神精简代码

1099 Build A Binary Search Tree (30分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.

Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.

figBST.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format left_index right_index, provided that the nodes are numbered from 0 to N−1, and 0 is always the root. If one child is missing, then −1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.
Output Specification:

For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.
Sample Input:

9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42

Sample Output:

58 25 82 11 38 67 45 73 42

自己的思路

思路:思路应该还是比较清晰的吧,根据最初给出的结点位置信息,构造出一个二叉树,然后把给出的数字全都按照中序遍历,从小到大填到二叉树里面。最后按照层序遍历输出。直到看了柳神的代码,我有点怀疑人生。。。。。。。

构建二叉树的思路:每个二叉树结点的data最初存储的是该节点的序号,根据需要就知道这个结点的左右孩子的结点序号了,构建左右孩子结点,赋值给根节点的左右孩子指针

易错点:使用链表构建二叉树,在循环里面一定得使用 node *newNode=new node();开辟新的结点,如果只是使用Node a; 或者 node a=node(); 每次循环a的结点地址是不变的,除非使用vector mapp这类的人家自己自动new一个和你声明的临时结构体数值都一样的新结构体 。另外别想着使用数组表示二叉树,你自己数数2的100次方是多大,测试点1 和测试点2是过不去的,数组大小不容易开,正在写博客的这个瓜皮已经尝试了

使用队列构造二叉树

另外,中序遍历别使用两个队列左手倒右手,多写了个赋值,直接导致内存容易爆炸
内存爆炸的实例:

#include <iostream>
#include <string>
using namespace std;
#include <algorithm>
#include <vector>
#include <queue>
vector<int> vec;
int number;
struct node
{

    int data;
    node *lchild,*rchild;
    node():data(-1),lchild(NULL),rchild(NULL) {}
};
//中序遍历

void medSearch(node *tree)
{
    if(tree==NULL)
        return;
    medSearch(tree->lchild);

    //就是中间了,需要赋值了
    //cout<<vec[number]<<' ';
    tree->data=vec[number++];

    medSearch(tree->rchild);
    return ;
}


int main()
{

    int N;
    cin>>N;
    node aa;
    node *tree=&aa;

    int save[101][2];
    fill(save[0],save[0]+101*2,-1);
    for(int i=0; i<N; i++)
    {
        int a,b;
        cin>>a>>b;//a是左孩子的结点编号,b是右孩子的结点编号
        save[i][0]=a;
        save[i][1]=b;

    }


    tree->data=0;

    queue<node*> sett;
    sett.push(tree);

    while(!sett.empty())
    {

        queue<node*> cache;
        while(!sett.empty())
        {
            node * cacheTree=sett.front();
            sett.pop();
            int correct=cacheTree->data;
            int a=save[cacheTree->data][0];
            int b=save[cacheTree->data][1];
            if(a!=-1)
            {
                node *l=new node();
                l->data=a;
                cacheTree->lchild=l;
                cache.push(cacheTree->lchild);
            }

            if(b!=-1)
            {
                node *r=new node();
                r->data=b;
                cacheTree->rchild=r;


                cache.push(cacheTree->rchild);
            }

        }
        sett=cache;//这一句和下面的循环重复了,导致了内存爆炸
        while(!cache.empty())
        {
            sett.push(cache.front());
            cache.pop();
        }
    }


    for(int i=0; i<N; i++)
    {
        int a;
        cin>>a;
        vec.push_back(a);
    }
    sort(vec.begin(),vec.end());

    medSearch(tree);

    queue<node*> que;
    //cout<<endl;

    que.push(tree);

    int first=1;
    while(!que.empty())
    {
        queue<node*> cache;
        while(!que.empty())
        {
            node *a=que.front();
            que.pop();
            if(first==1)
            {
                cout<<a->data;
                first=0;
            }
            else
                cout<<' '<<a->data;

            if(a->lchild!=NULL)
                cache.push(a->lchild);
            if(a->rchild!=NULL)
                cache.push(a->rchild);
        }
        que=cache;
    }
    return 0;
}

递归构造二叉树 推荐

自己AC的渣渣代码

#include <iostream>
#include <string>
using namespace std;
#include <algorithm>
#include <vector>
#include <queue>
vector<int> vec;
int number;
struct node
{

    int data;
    node *lchild,*rchild;
    node():data(-1),lchild(NULL),rchild(NULL) {}
};

//中序遍历
void medSearch(node *tree)
{
    if(tree==NULL)
        return;
    medSearch(tree->lchild);

    //就是中间了,需要赋值了
    //cout<<vec[number]<<' ';
    tree->data=vec[number++];

    medSearch(tree->rchild);
    return ;
}
//根据节点信息构造二叉树
void setTree(node *tree,int save[][2])
{
    int a=save[tree->data][0];
    int b=save[tree->data][1];
    if(a!=-1)
    {
        node *l=new node();
        l->data=a;
        tree->lchild=l;
        setTree(tree->lchild,save);
    }

    if(b!=-1)
    {
        node *r=new node();
        r->data=b;
        tree->rchild=r;


        setTree(tree->rchild,save);
    }

}
int main()
{

    int N;
    cin>>N;
    
    node *tree=new node();
	//保存结点信息
    int save[101][2];
    fill(save[0],save[0]+101*2,-1);
    for(int i=0; i<N; i++)
    {
        int a,b;
        cin>>a>>b;//a是左孩子的结点编号,b是右孩子的结点编号
        save[i][0]=a;
        save[i][1]=b;

    }


    tree->data=0;
    setTree(tree,save);

    


    for(int i=0; i<N; i++)
    {
        int a;
        cin>>a;
        vec.push_back(a);
    }
    sort(vec.begin(),vec.end());

    //中序遍历赋值
    medSearch(tree);



    //层序遍历输出
    queue<node*> sett;
    sett.push(tree);

    int first=1;
    while(!sett.empty())
    {
        queue<node*> cache;
        while(!sett.empty())
        {
            node *a=sett.front();
            sett.pop();
            if(first==1)
            {
                cout<<a->data;
                first=0;
            }
            else
                cout<<' '<<a->data;

            if(a->lchild!=NULL)
                cache.push(a->lchild);
            if(a->rchild!=NULL)
                cache.push(a->rchild);
        }
        sett=cache;
    }
    return 0;
}



柳神精简代码+自己的思考

下面是柳神的代码,必须去柳神博客膜拜一下,https://www.liuchuo.net/archives/2173
附加自己的一些思考:

  • 关于最后的层序遍历,其实可以在构建二叉树的时候记录每个结点的层次和左右次序,然后对所有结点使用sort排序,先按照层次排,层次一样按照左右次序的数字排
  • 我们可以使用先序遍历的递归方法构建二叉树,这个时候最先设置的结点其实就应该赋值最小的数字,省的我们构造好了二叉树,再进行先序遍历赋值了。所以整体算法就简洁成了柳神的方法了。

阔怕 !瑟瑟发抖


#include <iostream>
#include <algorithm>
using namespace std;
int n, cnt, b[100];
struct node {
    int data, l, r, index, lebel;
}a[110];
bool cmp(node x, node y) {
    if (x.lebel != y.lebel) return x.lebel < y.lebel;
    return x.index < y.index;
}
void dfs(int root, int index, int lebel) {
    if (a[root].l == -1 && a[root].r == -1) {
        a[root] = {b[cnt++], a[root].l, a[root].r, index, lebel};
    } else {
        if (a[root].l != -1) dfs(a[root].l, index * 2 + 1, lebel + 1);
        a[root] = {b[cnt++], a[root].l, a[root].r, index, lebel};
        if (a[root].r != -1) dfs(a[root].r, index * 2 + 2, lebel + 1);
    }
}
int main() {
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> a[i].l >> a[i].r;
    for (int i = 0; i < n; i++)
        cin >> b[i];
    sort(b, b + n);
    dfs(0, 0, 0);
    sort(a, a + n, cmp);
    for (int i = 0; i < n; i++) {
        if (i != 0) cout << " ";
        cout << a[i].data;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值