1123. Is It a Complete AVL Tree

#题目

按输入序列构造AVL树, 输出层次序遍历的结果, 和AVL树是否为完全二叉树

#一些小技巧:

#1. 树的初始化问题

我们可以让insert函数返回插入后新的树根(从而可以递归调用), 调用时采用 node = insert(node, val) 的方式, 从而统一了第一个节点和其他节点的处理, 极大地简化了判断逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
node* insert(node* p, int x){
if(!p){
p=new node();
p->val=x;
}else if(x<p->val){
p->left=insert(p->left,x);
}else{
p->right=insert(p->right,x);
}
return p;
}
// ...
int main(){
node*root=nullptr;
root=insert(root,1);
root=insert(root,2);
root=insert(root,3);
}

#体会:

  1. KISS, 简单的才是最好的
  2. 用好递归能节约大量代码
  3. 数据结构题不必在性能上过多纠结

#代码

(部分参考自网络)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
using namespace std;

struct node {
int val;
node *left = nullptr, *right = nullptr;
};

int depth(node *p)
{
return p ? 1 + max(depth(p->left), depth(p->right)) : 0;
}

node *rr(node *p)
{
node *lc = p->left;
p->left = lc->right;
lc->right = p;
return lc;
}

node *lr(node *p)
{
node *rc = p->right;
p->right = rc->left;
rc->left = p;
return rc;
}

node *lrr(node *p)
{
p->left = lr(p->left);
return rr(p);
}

node *rlr(node *p)
{
p->right = rr(p->right);
return lr(p);
}

node *insert(node *p, int x)
{
if (!p) {
p = new node();
p->val = x;
} else if (x < p->val) {
p->left = insert(p->left, x);
if (depth(p->left) - depth(p->right) > 1) {
if (x < p->left->val)
p = rr(p);
else
p = lrr(p);
}
} else {
p->right = insert(p->right, x);
if (depth(p->left) - depth(p->right) < -1) {
if (x > p->right->val)
p = lr(p);
else
p = rlr(p);
}
}
return p;
}

void trav(node *p)
{
int first = 1;
int empty = 0;
int comp = 1;
queue<node *> Q;
if (p) {
Q.push(p);
}
while (Q.size()) {
node *top = Q.front();
Q.pop();
if (!first) {
cout << " ";
}
first = 0;
cout << top->val;
if (top->left) {
if (empty) {
comp = 0;
}
Q.push(top->left);
} else {
empty = 1;
}
if (top->right) {
if (empty) {
comp = 0;
}
Q.push(top->right);
} else {
empty = 1;
}
}
cout << endl << (comp ? "YES" : "NO") << endl;
}

int main()
{
node *root = nullptr;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
root = insert(root, x);
}
trav(root);
return 0;
}