建立二叉搜索树 +判断是否为完全二叉树

include<bits/stdc++.h>

using namespace std;

struct node {
node* lt;
node* rt;
int data;
int id;
};

// 插入节点
node* Insert(node* root, int data) {
if (root == NULL) {
root = new node;
root->data = data;
root->lt = NULL;
root->rt = NULL;
return root;
}
if (data > root->data) {
root->lt = Insert(root->lt, data); // 左子树键值大
} else {
root->rt = Insert(root->rt, data); // 右子树键值小
}
return root;
}

// 层序遍历并判断是否是完全二叉树
void judge(node* root, int n) {
queue<node*> q;
q.push(root);
root->id = 1;
bool isComplete = true; // 是否是完全二叉树
bool hasNull = false; // 是否已经遇到空节点
int cnt = 0; // 统计节点数量

while (!q.empty()) {
    node* top = q.front();
    q.pop();
    cnt++;

    // 输出节点值
    if (cnt == 1) cout << top->data;
    else cout << " " << top->data;

    // 判断是否是完全二叉树
    if (top->lt) {
        if (hasNull) isComplete = false; // 如果遇到空节点后还有非空节点,不是完全二叉树
        q.push(top->lt);
        top->lt->id = top->id * 2;
    } else {
        hasNull = true;
    }
    if (top->rt) {
        if (hasNull) isComplete = false; // 如果遇到空节点后还有非空节点,不是完全二叉树
        q.push(top->rt);
        top->rt->id = top->id * 2 + 1;
    } else {
        hasNull = true;
    }
}

// 输出是否是完全二叉树
if (isComplete && cnt == n) {
    cout << endl << "YES" << endl;
} else {
    cout << endl << "NO" << endl;
}

}

int main() {
int n, tmp;
cin >> n;
node* head = NULL;

// 插入节点
for (int i = 1; i <= n; i++) {
    cin >> tmp;
    head = Insert(head, tmp);
}

// 层序遍历并判断是否是完全二叉树
judge(head, n);

return 0;

}

posted on 2025-03-19 21:30  下头小美  阅读(11)  评论(0)    收藏  举报