完全二叉树:假如该树的总层数为k层,则k-1层为满二叉树,第k层叶子节点尽量位于左子树
题目:http://xujcoj.com/home/problem/detail/2921
题解:
1.利用队列优先插入左节点
2.然后采取层次遍历,去访问每个节点
3.该写法要注意root根节点和左右节点都要在构造函数中进行初始化
AC代码:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
class Node
{
public:
Node* left;
Node* right;
int val;
Node(int x) :val(x),left(NULL),right(NULL){}
};
class Tree
{
private:
Node *root;
int val;
queue<Node*>Queue;
public:
Tree ():root(NULL){}
void insert(int x)
{
if (NULL == root)
{
root = new Node(x);
Queue.push(root);
return;
}
Node* p = Queue.front();
if (NULL == p->left)
{
p->left = new Node(x);
Queue.push(p->left);
return;
}
else if (NULL == p->right)
{
p->right = new Node(x);
Queue.push(p->right);
Queue.pop();//添加完该节点的右节点后就可以弹出 继续下一个
return;
}
}
void preOrder()
{
preOrder(root);
}
void preOrder(Node* p)
{
if (NULL != p)
{
cout << p->val << " ";
preOrder(p->left);
preOrder(p->right);
}
}
int layerOrder()
{
queue<Node*>q;
int sum = 0;
if (NULL!=root)
{
q.push(root);
}
else
{
return 0;
}
while (!q.empty())//直到为空
{
Node* node = q.front();//去寻找孩子
if (node!=NULL&&NULL != node->left)
{
if (node->left->val > node->val)
{
++sum;
}
q.push(node->left);
}
if (NULL!=node&&NULL != node->right)
{
if (node->right->val > node->val)
{
++sum;
}
q.push(node->right);
}
q.pop();
}
return sum;
}
};
int main()
{
Tree tree;//根节点root要初始化
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
tree.insert(x);
}
//tree.preOrder();
cout << tree.layerOrder() << endl;
}