樹的最大獨立集

#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;

ifstream fin("C:\\data19.in");

struct node
{
	node(int n=0):data(n),c(0),gc(1),parent(NULL),left(NULL),right(NULL){}
	int data;
	int c;
	int gc;
	struct node* parent;
	struct node* left;
	struct node* right;
};

class BSTree
{
public:
	BSTree():root(NULL){}
	void Init();
	node* SearchNode(node* nd,int n);
	void InsertNode(int n);
	void AfterOrderWalk(node*);
	node* GetRoot();
	void EmptyTree(node*);
	void print(node* nd);
	void FreshNode(node* nd);
	void MaxSubNode(node* nd);
private:
	node* root;
};

void BSTree::Init()
{
	int n;
	node* nd;
	fin>>n;
	nd=new node();
	nd->data=n;
	if(root==NULL)
		root=nd;
	else
		cout<<"根節點不爲空!"<<endl;
}

void BSTree::InsertNode(int n)
{
	node* datanode;
	datanode=new node();
	datanode->data=n;
	node *x,*y;
	x=root;
	y=NULL;
	while(x!=NULL)
	{
		y=x;
		if(x->data>n)
			x=x->left;
		else
			x=x->right;
	}
	datanode->parent=y;
	if(root==NULL)
		root=datanode;
	else
	{
		if(y->data>datanode->data)
			y->left=datanode;
		else
			y->right=datanode;
	}
}

void BSTree::AfterOrderWalk(node* nd)
{
	if(nd!=NULL)
	{
        ++total;
        AfterOrderWalk(nd->left);	            
		AfterOrderWalk(nd->right);
		FreshNode(nd);
	}
}

void BSTree::EmptyTree(node* nd)
{
	if(nd!=NULL)
	{
		EmptyTree(nd->left);
		EmptyTree(nd->right);
		delete nd;
		nd=NULL;
	}
}

node* BSTree::GetRoot()
{
    return root;
}

//採用中序遍歷的方法顯示樹的結構
void BSTree::print(node* nd)
{
     if(nd==NULL)
     {
         cout<<"NULL";
         return;
     }
     else
         cout<<nd->data;
     cout<<"(";
     print(nd->left);
     cout<<",";
     print(nd->right);
     cout<<")";
}

//核心代碼
//因爲要遍歷所有的子節點並在遍歷的過程中更新父節點的數據
//採用後序遍歷的方法
void BSTree::FreshNode(node* nd)
{
    if(nd==root)
        return;
    else
    {
        nd->parent->c+=nd->gc;
        nd->parent->gc+=nd->c;
    }
}

void BSTree::MaxSubNode(node *nd)
{
    if(nd->c > nd->gc)
          cout<<"此節點未被選擇,最大獨立集包含的元素數量爲"<<nd->c<<endl; 
    else
        cout<<"此節點被選擇,最大獨立集包含的元素數量爲"<<nd->gc<<endl; 
}

int main()
{
	int n;
	BSTree tree;
	tree.Init();
	while(fin>>n)
		tree.InsertNode(n);
	tree.print(tree.GetRoot());
	cout<<endl;
	tree.AfterOrderWalk(tree.GetRoot());
	cout<<endl;
	tree.MaxSubNode(tree.GetRoot());
        tree.EmptyTree(tree.GetRoot());
	system("pause");
	return 0;
}

發佈了48 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章