首页 > 技术文章 > PTA 7-1 是否完全二叉搜索树 (30分)

p1967914901 2020-04-29 14:55 原文

PTA 7-1 是否完全二叉搜索树 (30分)

将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。

输入格式:

输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。

输出格式:

将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO。

输入样例1:

9
38 45 42 24 58 30 67 12 51

输出样例1:

38 45 24 58 42 30 12 67 51
YES

输入样例2:

8
38 24 12 45 58 67 42 51

输出样例2:

38 45 24 58 42 12 67 51
NO

【程序思路】

输入数据然后根据二叉搜索树的插入操作建树。
判断是否完全二叉树的要点: 我们按照层次顺序遍历这颗树的过程中,对于任意一节点x

  • 如果x 有右子树,但是却没有左子树,这肯定不是完全二叉树
  • (如果x 有左子树,但是却没有右子树)|| ( 如果 x 左右子树都没有)【归纳来说就是没有右子树】,那么剩余的所有节点一定要为叶子节点

【程序实现】

#include<bits/stdc++.h>
using namespace std;
typedef struct tree{
    int data;
    struct tree *left;
    struct tree *right;
}*Tree;
Tree Insert(Tree root, int x) {
    if (!root) {
        root = new struct tree;
        root->data = x;
        root->left = root->right = NULL;
    }
    else {
        if (x > root->data)
            root->left = Insert(root->left, x);
        else if (x < root->data)
            root->right = Insert(root->right, x);
    }
    return root;
}
bool VisitJdg(Tree root) {
    queue<Tree> q;
    int flag = 0;
    bool jdg = true;
    if (root) {
        q.push(root);
        while(!q.empty()) {
            Tree t = q.front();
            q.pop();
            cout<<t->data;
            if (t->left)
                q.push(t->left);
            if (t->right)
                q.push(t->right);
            if (!q.empty())
                cout<<' ';
            if (!flag) {
                if (!t->left && t->right)
                    jdg = false;
                else if (!t->right)
                    flag = 1;
            }
            else {
                if (t->left || t->right)
                    jdg = false;
            }
        }
        cout<<endl;
    }
    return jdg;
}
int main(){
    Tree root = NULL;
    int n, x;
    cin>>n;
    for (int i = 0; i < n; i++) {
        cin>>x;
        root = Insert(root, x);
    }
    if(VisitJdg(root))
        cout<<"YES\n";
    else
        cout<<"NO\n";
	return 0;
}

推荐阅读