Independent set of tree with greedy algorithm

/*
Independent set on trees, which could be solved by greedy algorithm.
Key observation: if node v is a leaf, there exists a max cardinality independent
set containing v. 
http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/IntractabilityIII-2x2.pdf
The sample in this program is from wikipedia
https://en.wikipedia.org/wiki/Tree_traversal

*/


#include <iostream>
#include <vector>
#include <stack>
#include <Windows.h>

using namespace std;

struct node
{
	char data;
	struct node *left = nullptr;
	struct node *right = nullptr;
	bool visited = false;

	node() = default;
	node(char d) : data(d) {}
	node(char d, node *l, node *r) : data(d), left(l), right(r) {}
};

void independentSet(node *root, vector<char> &set)
{
	stack<node*> s;
	node *lst = nullptr;		// last visited node
	node *cur = root;			// current visit node
	node *top = nullptr;		// top node on stack
	
	while (!s.empty() || cur)	// postorder traverse
	{
		if (cur)
		{
			s.push(cur);
			cur = cur->left;
		}
		else
		{
			top = s.top();
			if (top->right && lst != top->right)
				cur = top->right;
			else
			{
				lst = top;
				if ((top->left == nullptr || top->left->visited == false) &&
					(top->right == nullptr || top->right->visited == false))
				{
					set.push_back(top->data);
					top->visited = true;
				}

				s.pop();
			}
		}
	}
}

int main()
{
	
	node *root = new node('F');
	root->left = new node('B');
	root->right = new node('G');
	root->left->left = new node('A');
	root->left->right = new node('D');
	root->left->right->left = new node('C');
	root->left->right->right = new node('E');
	root->right->right = new node('I');
	root->right->right->left = new node('H');
	
	/*
	node *root = new node('A');
	root->left = new node('B');
	root->right = new node('C');
	root->left->left = new node('D');
	root->left->left->left = new node('F');
	root->left->left->right = new node('G');
	root->left->left->right->left = new node('I');
	root->left->left->right->right = new node('J');
	root->right = new node('C');
	root->right->right = new node('E');
	root->right->right->left = new node('H');
	*/


	vector<char> set;
	independentSet(root, set);

	for (auto a : set)
		cout << a << " ";
	cout << endl;

	system("PAUSE");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值