完全二叉树应用

完全二叉树:假如该树的总层数为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值