1. 程式人生 > >是否為同一二叉搜尋樹

是否為同一二叉搜尋樹

題目描述:

判斷兩序列是否為同一二叉搜尋樹序列

輸入描述:

開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。
接下去一行是一個序列,序列長度小於10,包含(0~9)的數字,沒有重複數字,根據這個序列可以構造出一顆二叉搜尋樹。
接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉搜尋樹。

輸出描述:

如果序列相同則輸出YES,否則輸出NO。

輸入樣例:

2
567432
543267
576342
0

輸出樣例:

YES
NO

解題思路:

利用佇列來層次遍歷二叉樹求解。

AC程式碼:

#include <bits/stdc++.h>
using namespace std;

typedef struct TreeNode
{
    int data;
    TreeNode *lchild,*rchild;
}*Tree;
//利用佇列來實現二叉樹的層次遍歷
void LevelOrder(Tree root,vector<int> &v)  
{
    v.clear();   //一定先清空容器
    queue<Tree> q;
    q.push(root);
    while(!q.empty())   //佇列非空時
    {
        Tree bt = q.front();
        q.pop();
        v.push_back(bt->data);
        //將隊首結點的左孩子結點入佇列
        if(bt->lchild != NULL)
        {
            q.push(bt->lchild);
        }
        //將隊首結點的右孩子結點入佇列
        if(bt->rchild != NULL)
        {
            q.push(bt->rchild);
        }
    }
}

void Insert(Tree &root,int x)
{
    if(root == NULL)
    {
        root = new TreeNode;
        root->data = x;
        root->lchild = root->rchild = NULL;
    }
    else if(x < root->data)
    {
        Insert(root->lchild,x);
    }
    else
    {
        Insert(root->rchild,x);
    }
}

Tree Str2Tree(string s)     //根據字串得到一棵樹
{
    Tree bt = NULL;
    for (int i = 0; i < s.length(); ++i)
    {
        Insert(bt,s[i]);
    }
    return bt;
}

int main()
{
    int n;
    string str,temp;
    vector<int> a,b;
    while(cin >> n && n)
    {
        cin >> str;
        Tree bt = Str2Tree(str);
        LevelOrder(bt,a);
        for (int i = 0; i < n; ++i)
        {
            cin >> temp;
            Tree temp_bt = Str2Tree(temp);
            LevelOrder(temp_bt,b);
            if(a == b)
            {
                cout << "YES" << endl;
            }
            else
            {
                cout << "NO" << endl;
            }
        }
    }
    return 0;
}