The city Valera lives in is going to hold elections to the city Parliament.

The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.

There are n candidates running the elections. Let's enumerate all candidates in some way by integers from 1 to n, inclusive. If the candidate number i will be elected in the city Parliament, he will perform exactly one promise — to repair all problem roads on the way from the i-th district to the district 1, where the city Parliament is located.

Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.

Input

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of districts in the city.

Then n - 1 lines follow. Each line contains the description of a city road as three positive integers xi, yi, ti (1 ≤ xi, yi ≤ n, 1 ≤ ti ≤ 2) — the districts connected by the i-th bidirectional road and the road type. If ti equals to one, then the i-th road isn't the problem road; if ti equals to two, then the i-th road is the problem road.

It's guaranteed that the graph structure of the city is a tree.

Output

In the first line print a single non-negative number k — the minimum size of the required subset of candidates. Then on the second line print k space-separated integers a1, a2, ... ak — the numbers of the candidates that form the required subset. If there are multiple solutions, you are allowed to print any of them.

Examples

Input

5
1 2 2
2 3 2
3 4 2
4 5 2


Output

1
5 


Input

5
1 2 1
2 3 2
2 4 1
4 5 1


Output

1
3 


Input

5
1 2 2
1 3 2
1 4 2
1 5 2


Output

4
5 4 3 2

Difficulty: MEDIUM_HARD
Tags: Tree algorithms

Graph algorithms

Graph traversal

Starter code:

Solutions:
n = int(input())
white = []
g = [[] for _ in range(n)]
d = [0] * n
for i in range(n - 1):
	(x, y, t) = list(map(int, input().strip().split()))
	x -= 1
	y -= 1
	if x >= 0 and y >= 0 and (x < n) and (y < n):
		g[x].append(y)
		g[y].append(x)
	if t == 2:
		white.append((x, y))
(stack, parent) = ([0], [-1] * n)
while stack:
	u = stack.pop()
	for v in g[u]:
		parent[v] = u
		if len(g[v]) > 1:
			g[v].remove(u)
			stack.append(v)
color = [0] * n
for (u, v) in white:
	color[u if parent[u] == v else v] = 1
color[0] = 2
for (u, c) in enumerate(color):
	if c == 1:
		u = parent[u]
		while color[u] != 2:
			(color[u], u) = (2, parent[u])
res = [i for (i, c) in enumerate(color, 1) if c == 1]
print(len(res))
print(' '.join([str(x) for x in res]))


from sys import stdin
from bisect import bisect_left
from time import perf_counter
t0 = perf_counter()
n = int(input())
all = stdin.read().strip()
xyt_list = [list(map(int, l.split())) for l in all.split('\n')]
node2nodes = [[] for i in range(n + 1)]
xy2t = {}
for xyt in xyt_list[:]:
	(x, y, t) = (xyt[0], xyt[1], xyt[2])
	node2nodes[x].append(y)
	node2nodes[y].append(x)
	xy2t[x, y] = t
	xy2t[y, x] = t
parent = [0] * (n + 1)
children = [[] for i in range(n + 1)]
in_tree = [False] * (n + 1)
in_tree[1] = True
leaves = [1]
while leaves:
	x = leaves.pop()
	for y in node2nodes[x]:
		if not in_tree[y]:
			in_tree[y] = True
			parent[y] = x
			children[x].append(y)
			leaves.append(y)
for i in range(1, len(children)):
	if len(children[i]) == 0:
		leaves.append(i)

def dfs(node, broken_nodes):
	subtree_broken = False
	for child in children[node]:
		subtree_broken = dfs(child, broken_nodes) or subtree_broken
	if parent[node] == 0:
		return subtree_broken
	if not subtree_broken and xy2t[parent[node], node] == 2:
		subtree_broken = True
		broken_nodes.append(node)
	return subtree_broken

def dfs2(node, broken_nodes):
	stack = [1]
	visited = [0] * (n + 1)
	broken = []
	while stack:
		node = stack[-1]
		if not visited[node]:
			visited[node] = True
			for child in children[node]:
				stack.append(child)
		else:
			stack.pop()
			subtree_broken = False
			for i in range(len(children[node])):
				subtree_broken = subtree_broken or broken.pop()
			if not subtree_broken and parent[node] != 0 and (xy2t[parent[node], node] == 2):
				subtree_broken = True
				broken_nodes.append(node)
			broken.append(subtree_broken)
selected = []
dfs2(1, selected)
print(len(selected))
print(' '.join((str(x) for x in selected)))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def main():
	d = defaultdict(list)
	s = set()
	n = int(input())
	for i in range(n - 1):
		(x, y, t) = map(int, input().split())
		d[x].append(y)
		d[y].append(x)
		if t == 2:
			s.add((x, y))
	p = [0] * (n + 1)
	visited = [0] * (n + 1)
	ans = []

	def dfs(curr, s1, ances):
		visited[curr] = 1
		for i in d[curr]:
			if visited[i] == 0:
				dfs(i, s1, curr)
				p[curr] = max(p[i], p[curr])
		if (curr, ances) in s and p[curr] == 0:
			p[curr] = 1
			ans.append(curr)
		elif (ances, curr) in s and p[curr] == 0:
			p[curr] = 1
			ans.append(curr)
	dfs(1, s, -1)
	print(len(ans))
	print(*ans)
t = threading.Thread(target=main)
t.start()
t.join()


n = int(input())
q = []
p = [[] for i in range(n + 1)]
for i in range(n - 1):
	(a, b, t) = [int(i) for i in input().split()]
	p[a].append(b)
	p[b].append(a)
	if t == 2:
		q.append((a, b))
if len(q) == 0:
	print(0)
else:
	r = [1]
	t = [0] * (n + 1)
	while len(r) > 0:
		a = r.pop()
		for b in p[a]:
			t[b] = a
			if len(p[b]) > 1:
				p[b].remove(a)
				r.append(b)
	s = [0] * (n + 1)
	for (a, b) in q:
		if t[a] == b:
			s[a] = 1
		else:
			s[b] = 1
	s[1] = 2
	for a in range(1, n + 1):
		if s[a] == 1:
			a = t[a]
			while s[a] != 2:
				s[a] = 2
				a = t[a]
	s = [i for (i, j) in enumerate(s) if j == 1]
	print(len(s))
	print(' '.join([str(i) for i in s]))


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
INF = 999999999999999999999999
alphabets = 'abcdefghijklmnopqrstuvwxyz'

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

class SegTree:

	def __init__(self, n):
		self.N = 1 << n.bit_length()
		self.tree = [0] * (self.N << 1)

	def update(self, i, j, v):
		i += self.N
		j += self.N
		while i <= j:
			if i % 2 == 1:
				self.tree[i] += v
			if j % 2 == 0:
				self.tree[j] += v
			(i, j) = (i + 1 >> 1, j - 1 >> 1)

	def query(self, i):
		v = 0
		i += self.N
		while i > 0:
			v += self.tree[i]
			i >>= 1
		return v

def SieveOfEratosthenes(limit):
	isPrime = [True] * (limit + 1)
	isPrime[0] = isPrime[1] = False
	primes = []
	for i in range(2, limit + 1):
		if not isPrime[i]:
			continue
		primes += [i]
		for j in range(i * i, limit + 1, i):
			isPrime[j] = False
	return primes

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		n = ri()
		problem_roads = {}
		graph = [[] for i in range(n + 1)]
		visited = [0] * (n + 1)
		val = [0] * (n + 1)
		par = [0] * (n + 1)
		for i in range(n - 1):
			(x, y, t) = ria()
			graph[x].append(y)
			graph[y].append(x)
			if t == 2:
				problem_roads[x, y] = 1
				problem_roads[y, x] = 1
		ans = []

		def dfs():
			n = len(graph)
			(visited, finished) = ([False] * n, [False] * n)
			stack = [1]
			while stack:
				start = stack[-1]
				if not visited[start]:
					visited[start] = True
					for child in graph[start]:
						if not visited[child]:
							stack.append(child)
				else:
					stack.pop()
					for child in graph[start]:
						if finished[child]:
							if (start, child) in problem_roads:
								val[start] += 1
							val[start] += val[child]
						par[child] = start
					finished[start] = True
		dfs()
		for i in range(2, n + 1):
			if val[i] == 0 and val[par[i]] and ((i, par[i]) in problem_roads):
				ans.append(i)
		wi(len(ans))
		wia(ans)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


def find_problem(edges, node, par, problems):
	flag = False
	for (ch, problem) in edges.get(node, []):
		if ch != par:
			child_problem = find_problem(edges, ch, node, problems)
			if not child_problem and problem:
				problems.append(str(ch))
			flag = flag or problem or child_problem
	return flag

def main():
	from collections import defaultdict
	n = list(map(int, input().split()))
	n = n[0]
	edges = defaultdict(list)
	for _ in range(n - 1):
		(x, y, problem) = list(map(int, input().split()))
		edges[x].append((y, problem == 2))
		edges[y].append((x, problem == 2))
	problems = []
	ans = find_problem(edges, node=1, par=0, problems=problems)
	print(len(problems))
	print(' '.join(problems))
import sys
import threading
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


from collections import *
from sys import stdin

class graph:

	def __init__(self, gdict=None):
		if gdict is None:
			gdict = defaultdict(list)
		(self.gdict, self.edges, self.l) = (gdict, [], defaultdict(int))

	def add_edge(self, node1, node2, w=None):
		self.gdict[node1].append([node2, w])
		self.gdict[node2].append([node1, w])
		self.l[node1] += 1
		self.l[node2] += 1

	def dfsUtil(self, v):
		(stack, visit, nodes) = ([[v, 0]], [0] * (n + 1), [0] * (n + 1))
		visit[v] = 1
		while stack:
			(s, pre) = stack.pop()
			for (i, j) in self.gdict[s]:
				if not visit[i]:
					visit[i] = 1
					if j == 2:
						nodes[i] = 1
						nodes[pre] = 0
						stack.append([i, i])
					else:
						stack.append([i, pre])
		ans = list((str(i) for i in range(n + 1) if nodes[i]))
		print(len(ans))
		print(' '.join(ans))
(n, g, s1) = (int(stdin.readline()), graph(), 0)
for i in range(n - 1):
	(u, v, r) = map(int, stdin.readline().split())
	g.add_edge(u, v, r)
	if r == 2:
		s1 += 1
g.dfsUtil(1)


import sys

def readInputs():
	global n, lAdj, setToRepair
	n = int(f.readline()[:-1])
	lAdj = [[] for _ in range(n)]
	setToRepair = set()
	for _ in range(n - 1):
		(a, b, c) = map(int, f.readline().split())
		lAdj[a - 1] += [b - 1]
		lAdj[b - 1] += [a - 1]
		if c == 2:
			setToRepair.add((a - 1, b - 1))
			setToRepair.add((b - 1, a - 1))

def calcHauteurs():
	global nodesSorted, hauteurs
	stack = [0]
	hauteurs = [-1 for i in range(0, n)]
	hauteurs[0] = 0
	while len(stack) > 0:
		curNode = stack.pop()
		for succ in lAdj[curNode]:
			if hauteurs[succ] == -1:
				hauteurs[succ] = hauteurs[curNode] + 1
				stack.append(succ)
	nodesSorted = list(range(1, n))
	nodesSorted.sort(key=lambda x: hauteurs[x], reverse=True)

def solve():
	covered = [False for _ in range(n)]
	res = []
	calcHauteurs()
	for node in nodesSorted:
		for succ in lAdj[node]:
			if hauteurs[succ] < hauteurs[node]:
				if (node, succ) in setToRepair:
					if not covered[node]:
						covered[node] = True
						res += [node + 1]
				if covered[node]:
					covered[succ] = True
	return res

def tests():
	global f
	bFail = False
	for i in range(1, 28):
		f = open('test' + str(i) + '.txt')
		readInputs()
		_ = int(f.readline()[:-1])
		lEx = list(map(int, f.readline().split()))
		lEx.sort()
		lExpect = str(lEx)
		res = str(solve())
		if res != lExpect:
			print('TEST', i, 'FAILED !' + ' Found :', res, ', Expected :', lExpect)
			bFail = True
		else:
			print('TEST', i, 'PASSED')
	if not bFail:
		print('\n--- ALL OF THE ' + str(i) + ' TESTS HAVE SUCCEEDED ---')

def main():
	global f
	i = 2
	if i == 1:
		tests()
		return
	f = sys.stdin
	readInputs()
	res = solve()
	print(len(res))
	print(' '.join(map(str, res)))
main()


import sys
from math import sqrt, gcd, ceil, log
from collections import defaultdict, Counter, deque
input = sys.stdin.readline
read = lambda : list(map(int, input().strip().split()))
sys.setrecursionlimit(200000)

def main():
	n = int(input())
	adj = defaultdict(list)
	problem = set()
	for i in range(n - 1):
		(x, y, t) = read()
		adj[x].append(y)
		adj[y].append(x)
		if t == 2:
			problem.add((x, y))
	parent = defaultdict(int)
	order = []

	def dfs():
		stk = [(1, 0)]
		while stk:
			(node, par) = stk.pop()
			order.append(node)
			parent[node] = par
			for child in adj[node]:
				if child != par:
					stk.append((child, node))
	dfs()
	dic = defaultdict(int)
	ans = []
	for i in range(n - 1, -1, -1):
		child = order[i]
		par = parent[order[i]]
		if dic[child]:
			dic[par] += dic[child]
		elif (child, par) in problem or (par, child) in problem:
			ans.append(child)
			dic[par] += 1
	print(len(ans))
	print(*ans)
main()


import sys
import threading
from collections import defaultdict
adj = defaultdict(list)
n = int(input())
for _ in range(n - 1):
	(x, y, b) = list(map(int, input().split()))
	adj[x].append((y, b))
	adj[y].append((x, b))

def fun(node, par, li):
	y = 0
	dam = 1
	for (ch, b) in adj[node]:
		if ch == par:
			dam = b
		else:
			y |= fun(ch, node, li)
	if y == 0 and dam == 2:
		li.append(node)
		y = 1
	return y

def main():
	li = []
	fun(1, 0, li)
	print(len(li))
	if li:
		print(' '.join(map(str, li)))
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque

def dfs():
	stack = [[1, 0]]
	while stack:
		x = stack.pop()
		level[x[1]].append(x[0])
		for i in graph[x[0]]:
			stack.append([i, x[1] + 1])
			graph[i].remove(x[0])
			papa[i] = x[0]
n = int(input())
graph = {i: set() for i in range(1, n + 1)}
condi = {}
papa = [0, 0]
l = [0, 0]
level = [[] for i in range(n + 1)]
for i in range(n - 1):
	(a, b, t) = map(int, input().split())
	condi[a, b] = t
	graph[a].add(b)
	graph[b].add(a)
	papa.append(0)
	l.append(0)
ans = []
dfs()
for i in range(len(level) - 1, -1, -1):
	for j in level[i]:
		if l[j] > 0:
			l[papa[j]] = 1
			continue
		if (j, papa[j]) in condi:
			if condi[j, papa[j]] == 2:
				if l[j] == 0:
					ans.append(j)
					l[papa[j]] = 1
			else:
				l[papa[j]] = max(l[j], l[papa[j]])
		elif (papa[j], j) in condi:
			if condi[papa[j], j] == 2:
				if l[j] == 0:
					ans.append(j)
					l[papa[j]] = 1
			else:
				l[papa[j]] = max(l[j], l[papa[j]])
print(len(ans))
print(*ans)


import sys
input = sys.stdin.readline

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def dfs():
	st = [(1, 1)]
	while st:
		(node, p) = st.pop()
		vis[node] = 1
		for (v, k) in g[node]:
			if vis[v] == 0:
				if k == 2:
					st.append((v, v))
					ans[v] = 1
					ans[p] = 0
				else:
					st.append((v, p))
from collections import Counter
import math
import bisect
from collections import deque
n = int(input())
vis = [0] * int(n + 1)
g = [[] for i in range(n + 1)]
for i in range(n - 1):
	(u, v, s) = int_array()
	g[u].append((v, s))
	g[v].append((u, s))
ans = [0] * (n + 1)
dfs()
print(ans.count(1))
for i in range(n + 1):
	if ans[i] == 1:
		print(i, end=' ')


n = int(input())
adj = [[] for i in range(n + 1)]
vis = [0 for i in range(n + 1)]
prt = [0 for i in range(n + 1)]
curr_sum = [0 for i in range(n + 1)]
res = []
edges = [list(map(int, input().split())) for _ in range(n - 1)]
for (u, v, w) in edges:
	adj[u].append([v, w])
	adj[v].append([u, w])

def dfs(u):
	stk = [u]
	vis[u] = 1
	while stk:
		u = stk.pop()
		if vis[u] == 2:
			for (v, w) in adj[u]:
				if v != prt[u]:
					if curr_sum[v] == 0 and w == 2:
						res.append(v)
					curr_sum[u] += curr_sum[v]
					curr_sum[u] += w - 1
		elif vis[u] == 1:
			stk.append(u)
			for (v, w) in adj[u]:
				if v != prt[u] and vis[v] == 0:
					vis[v] = 1
					prt[v] = u
					stk.append(v)
			vis[u] = 2
dfs(1)
print(str(len(res)))
print(' '.join(map(str, res)))


n = int(input())
u = [[] for _ in range(n + 1)]
v = [[] for _ in range(n + 1)]
s = [0] * (n + 1)
for _ in range(n - 1):
	(a, b, c) = map(int, input().split())
	u[a].append(b)
	u[b].append(a)
	if c == 2:
		s[a] = 1
		s[b] = 1
d = [0] * (n + 1)
stack = [[1, 0, 1]]
while stack:
	(curr, prev, last) = stack.pop()
	if s[curr] == 1:
		d[curr] = 1
		d[last] = 0
		last = curr
	for i in u[curr]:
		if i == prev:
			continue
		stack.append([i, curr, last])
final = []
for i in range(n + 1):
	if d[i] == 1:
		final.append(i)
print(len(final))
print(*final)


from sys import stdin
n = int(stdin.readline())
from collections import defaultdict
g = defaultdict(list)
for i in range(n - 1):
	(a, b, c) = map(int, stdin.readline().split())
	g[a - 1].append((b - 1, c))
	g[b - 1].append((a - 1, c))
stack = []
stack.append((0, -1, False))
ans = []
vis = [0] * n
dp = [0] * n
while stack:
	(cur, par, state) = stack.pop()
	vis[cur] = 1
	c = 0
	for (chd, lbl) in g[cur]:
		if chd == par:
			continue
		elif vis[chd] == 0:
			c += 1
	if c > 0:
		stack.append((cur, par, state))
		for (chd, lbl) in g[cur]:
			if chd != par:
				if vis[chd] == 0:
					if lbl == 2:
						stack.append((chd, cur, True))
					else:
						stack.append((chd, cur, False))
	else:
		for (chd, lbl) in g[cur]:
			if chd != par:
				dp[cur] += dp[chd]
		if state == True and dp[cur] == 0:
			dp[cur] += 1
			ans.append(cur + 1)
print(len(ans))
print(*ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	n = int(input())
	tree = [[] for _ in range(n + 1)]
	ans = set()
	for _ in range(n - 1):
		(x, y, t) = map(int, input().split())
		if t == 2:
			ans.add(x)
			ans.add(y)
		tree[x].append(y)
		tree[y].append(x)
	idx = [0] * (n + 1)
	stack = [(1, 0, 1)]
	while stack:
		(x, p, prev) = stack[-1]
		y = idx[x]
		if y == len(tree[x]):
			stack.pop()
		else:
			z = tree[x][y]
			if z != p:
				if z in ans:
					if prev in ans:
						ans.remove(prev)
					prev = z
				stack.append((z, x, prev))
			idx[x] += 1
	print(len(ans))
	print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin

def main():
	n = int(input())
	(bad, g) = ([], [[] for _ in range(n)])
	for s in stdin.read().splitlines():
		(u, v, t) = (int(w) - 1 for w in s.split())
		g[u].append(v)
		g[v].append(u)
		if t:
			bad.append((u, v))
	if not bad:
		print(0)
		return
	(stack, parent) = ([0], [-1] * n)
	while stack:
		u = stack.pop()
		for v in g[u]:
			parent[v] = u
			if len(g[v]) > 1:
				g[v].remove(u)
				stack.append(v)
	color = [0] * n
	for (u, v) in bad:
		color[u if parent[u] == v else v] = 1
	color[0] = 2
	for (u, c) in enumerate(color):
		if c == 1:
			u = parent[u]
			while color[u] != 2:
				(color[u], u) = (2, parent[u])
	res = [i for (i, c) in enumerate(color, 1) if c == 1]
	print(len(res))
	print(' '.join(map(str, res)))
main()


import sys
from collections import defaultdict
from collections import deque
from types import GeneratorType
input = sys.stdin.readline

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc

def get_adj_mat(src, dst, problem_roads):
	matrix = defaultdict(list)
	for (src_i, dst_i, problem_i) in zip(src, dst, problem_roads):
		matrix[src_i].append((dst_i, problem_i))
		matrix[dst_i].append((src_i, problem_i))
	return matrix

@bootstrap
def set_last_bad_city(curr_index, parent_index, is_road_bad, adj_mat, last_bad_city):
	all_childs_good = True
	for (child_index, is_bad) in adj_mat[curr_index]:
		if child_index != parent_index:
			is_child_bad = (yield set_last_bad_city(child_index, curr_index, is_bad, adj_mat, last_bad_city))
			all_childs_good = all_childs_good and is_child_bad
	if not is_road_bad and all_childs_good:
		yield True
	if is_road_bad and all_childs_good:
		last_bad_city[curr_index] = True
	yield False

def solve(src, dst, problem_roads, n):
	adj_mat = get_adj_mat(src, dst, problem_roads)
	last_bad_city = [False] * n
	root = 0
	set_last_bad_city(root, root, False, adj_mat, last_bad_city)
	ans = [i + 1 for i in range(1, n) if last_bad_city[i]]
	print(len(ans))
	print(*ans)
n = int(input())
(src, dst, problem_roads) = ([], [], [])
for _ in range(n - 1):
	(src_i, dst_i, cond) = [int(val) for val in input().split()]
	(src.append(src_i - 1), dst.append(dst_i - 1), problem_roads.append(bool(cond - 1)))
solve(src, dst, problem_roads, n)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def pow(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def lcm(a, b):
	return abs(a // gcd(a, b) * b)

def solve():
	n = N()
	defect = set()
	g = [[] for _ in range(n)]
	for _ in range(n - 1):
		(a, b, t) = sep()
		a -= 1
		b -= 1
		g[a].append(b)
		g[b].append(a)
		if t == 2:
			defect.add((a, b))
			defect.add((b, a))
	dp = [0] * n
	ans = []

	@iterative
	def dfs(v, p):
		if len(g[v]) == 1 and g[v][0] == p:
			yield
		co = 0
		for c in g[v]:
			if c == p:
				continue
			yield dfs(c, v)
			if (c, v) in defect:
				if dp[c] == 0:
					co += 1
					ans.append(c + 1)
				else:
					co += dp[c]
			else:
				co += dp[c]
		dp[v] = co
		yield
	dfs(0, 0)
	print(dp[0])
	print(*ans)
solve()


import sys
input = sys.stdin.readline

def dfs():
	st = [(1, 1)]
	while st:
		(x, p) = st.pop()
		vis[x] = 1
		for (v, k) in g[x]:
			if not vis[v]:
				if k == 2:
					ans[v] = 1
					ans[p] = 0
					st.append((v, v))
				else:
					st.append((v, p))
n = int(input())
g = [[] for i in range(n + 1)]
for i in range(n - 1):
	(x, y, k) = map(int, input().split())
	g[x].append((y, k))
	g[y].append((x, k))
(ans, vis) = ([0] * (n + 1), [0] * (n + 1))
dfs()
print(ans.count(1))
for i in range(n + 1):
	if ans[i] == 1:
		print(i, end=' ')
print()


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from math import *
from collections import defaultdict as dd, deque

def data():
	return sys.stdin.readline().strip()

def mdata():
	return map(int, data().split())
sys.setrecursionlimit(100000)

def dfs(x):
	s = deque()
	s.append([x, x])
	while len(s) > 0:
		(v, par) = s.popleft()
		vis[v] = 1
		for i in g[v]:
			if vis[i] == 0:
				if g[v][i] == 2:
					ans[par] = 0
					ans[i] = 1
					s.append([i, i])
				else:
					s.append([i, par])
n = int(data())
g = dd(dict)
for i in range(n - 1):
	(a, b, c) = mdata()
	g[a][b] = c
	g[b][a] = c
ans = [0] * (n + 1)
vis = [0] * (n + 1)
dfs(1)
cnt = 0
for i in ans:
	cnt += i
print(cnt)
for i in range(n + 1):
	if ans[i] == 1:
		print(i, end=' ')
print()


n = int(input())
listaAdj = [[] for i in range(n)]
estradasRuins = set()
for i in range(n - 1):
	road_input = [int(x) for x in input().split()]
	a = road_input[0] - 1
	b = road_input[1] - 1
	ruim = road_input[2] == 2
	listaAdj[a].append(b)
	listaAdj[b].append(a)
	if ruim:
		estradasRuins.add(a)
		estradasRuins.add(b)
stack = [(index, [0], 0) for index in listaAdj[0]]
while stack:
	cur = stack.pop()
	to_idx = cur[0]
	parents = cur[1]
	from_idx = cur[2]
	if to_idx in estradasRuins:
		estradasRuins.difference_update(parents)
		parents = []
	listaAdj[to_idx].remove(from_idx)
	parents.append(to_idx)
	stack += [(index, parents, to_idx) for index in listaAdj[to_idx]]
candidatos = [idx + 1 for idx in estradasRuins]
print(len(candidatos))
print(*candidatos)


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7

def solve():
	N = getInt()
	(graph, prob) = (dd(set), dd(int))
	for n in range(N - 1):
		(A, B, T) = getInts()
		graph[A].add(B)
		graph[B].add(A)
		if A > B:
			(A, B) = (B, A)
		prob[A, B] = T
	probs = []
	prob_set = set()

	def bfs(node):
		queue = dq([(node, 0)])
		visited.add(node)
		parent[node] = 0
		while queue:
			(node, level) = queue.popleft()
			count = 0
			for neighbour in graph[node]:
				if neighbour not in visited:
					queue.append((neighbour, level + 1))
					visited.add(neighbour)
					parent[neighbour] = node
					count += 1
					if prob[min(node, neighbour), max(node, neighbour)] == 2:
						probs.append((level, node, neighbour))
						prob_set.add((node, neighbour))
			if not count:
				leaf.append(node)
	parent = dd(int)
	leaf = []
	visited = set()
	bfs(1)
	visited = set()
	ans = []
	probs.sort()
	while probs:
		(level, par, child) = probs.pop()
		if (par, child) not in prob_set:
			continue
		prob_set.remove((par, child))
		ans.append(child)
		visited.add(child)
		child = par
		while True:
			visited.add(child)
			par = parent[child]
			if not par:
				break
			if (par, child) in prob_set:
				prob_set.remove((par, child))
			if par in visited:
				break
			child = par
	print(len(ans))
	print(*ans)
	return
solve()


import math, sys, bisect, heapq
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
int1 = lambda x: int(x) - 1
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))
ilelec = lambda : map(int1, input().split())
alelec = lambda : list(map(int1, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])
G = defaultdict(list)

def addEdge(a, b, c):
	G[a].append((b, c))
	G[b].append((a, c))

def dfs():
	s = deque()
	s.append((1, 1))
	while s:
		(p, mp) = s.pop()
		vis[p] = True
		for (c, k) in G[p]:
			if not vis[c]:
				if k == 1:
					s.append((c, mp))
				else:
					Ans[mp] = 0
					Ans[c] = 1
					s.append((c, c))
N = int(input())
for i in range(N - 1):
	(x, y, t) = ilele()
	addEdge(x, y, t)
vis = [False] * (N + 1)
Ans = [0] * (N + 1)
dfs()
A = []
for i in range(1, N + 1):
	if Ans[i]:
		A.append(i)
print(len(A))
print(*A)


from sys import stdin

def main():
	n = int(stdin.readline())
	adj = [[] for _ in range(n)]
	for _ in range(n - 1):
		(a, b, c) = map(int, stdin.readline().split())
		adj[a - 1].append((b - 1, c))
		adj[b - 1].append((a - 1, c))
	ans = []
	d = [0] * n
	visited = [False] * n
	stack = [(0, -1, False)]
	while stack:
		(curr, parent, state) = stack.pop()
		visited[curr] = True
		count = 0
		for p in adj[curr]:
			if not visited[p[0]]:
				if p[0] != parent:
					count += 1
		if count > 0:
			stack.append((curr, parent, state))
			for p in adj[curr]:
				if not visited[p[0]]:
					if p[0] != parent:
						if p[1] == 2:
							stack.append((p[0], curr, True))
						else:
							stack.append((p[0], curr, False))
		else:
			for p in adj[curr]:
				if p[0] != parent:
					d[curr] += d[p[0]]
			if state and d[curr] == 0:
				d[curr] += 1
				ans.append(curr + 1)
	print(len(ans))
	print(*ans)
main()


def dfs(grafos, quebrados):
	(l1, l2) = ([1], [0] * (n + 1))
	while len(l1) != 0:
		popado = l1.pop()
		for adj in grafos[popado]:
			l2[adj] = popado
			if len(grafos[adj]) > 1:
				grafos[adj].remove(popado)
				l1.append(adj)
	s = [0] * (n + 1)
	for (a, b) in quebrados:
		if l2[a] == b:
			s[a] = 1
		else:
			s[b] = 1
	s[1] = 2
	for a in range(1, n + 1):
		if s[a] == 1:
			a = l2[a]
			while s[a] != 2:
				s[a] = 2
				a = l2[a]
	s = [i for (i, j) in enumerate(s) if j == 1]
	print(len(s))
	print(' '.join([str(i) for i in s]))
n = int(input())
quebrados = []
grafos = [[] for i in range(n + 1)]
for estradas in range(n - 1):
	(a, b, t) = map(int, input().split())
	grafos[a].append(b)
	grafos[b].append(a)
	if t == 2:
		quebrados.append((a, b))
if len(quebrados) == 0:
	print(0)
else:
	dfs(grafos, quebrados)


n = int(input())
g = [[] for _ in range(n + 1)]
for i in range(n - 1):
	(x, y, t) = map(int, input().split())
	g[x].append((y, t))
	g[y].append((x, t))
stack = []
stack.append((1, 1))
vis = [0] * (n + 1)
vis[1] = 1
ans = [0] * (n + 1)
while stack:
	(road, t) = stack.pop()
	for (adj, k) in g[road]:
		if not vis[adj]:
			if k == 2:
				ans[t] = 0
				ans[adj] = 1
				vis[adj] = 1
				stack.append((adj, adj))
			else:
				vis[adj] = 1
				stack.append((adj, t))
print(sum(ans))
s = []
for i in range(n + 1):
	if ans[i]:
		s.append(str(i))
print(' '.join(s))


from sys import stdin
input = stdin.readline
n = int(input())
g = [[] for i in range(n)]
color = [0] * n
for _ in range(n - 1):
	(x, y, t) = map(int, input().split())
	g[x - 1].append(y - 1)
	g[y - 1].append(x - 1)
	if t == 2:
		color[x - 1] = color[y - 1] = 1
dp = [0] * n
q = [(-1, 0, 0)]
while q:
	(par, ver, state) = q.pop()
	if state == 0:
		q.append((par, ver, 1))
		for to in g[ver]:
			if par != to:
				q.append((ver, to, 0))
		continue
	else:
		if len(g[ver]) == 1 and ver != 0:
			dp[ver] = color[ver]
			continue
		val = color[ver]
		for to in g[ver]:
			if par != to:
				val += dp[to]
		dp[ver] = val
a = []
for i in range(n):
	if dp[i] == 1:
		a.append(i + 1)
print(len(a))
print(*a)


import sys
(NOT_SEEN, SEEN, COMPLETE) = (1, 2, 3)
N = int(sys.stdin.readline())
edge = [[] for i in range(N + 1)]
status = [NOT_SEEN for i in range(N + 1)]
parent = [0 for i in range(N + 1)]
result = [0 for i in range(N + 1)]
ans = []
for i in range(N - 1):
	(_u, _v, _t) = map(int, sys.stdin.readline().split())
	edge[_u].append([_v, _t])
	edge[_v].append([_u, _t])
stack = []

def dfs(u):
	stack.append(u)
	status[u] = SEEN
	while len(stack) != 0:
		u = stack.pop()
		if status[u] == COMPLETE:
			for (_v, _t) in edge[u]:
				if _v != parent[u]:
					if result[_v] == 0 and _t == 2:
						ans.append(_v)
					result[u] += result[_v]
					result[u] += _t - 1
		elif status[u] == SEEN:
			stack.append(u)
			for (_v, _t) in edge[u]:
				if _v != parent[u] and status[_v] == NOT_SEEN:
					status[_v] = SEEN
					parent[_v] = u
					stack.append(_v)
			status[u] = COMPLETE
dfs(1)
sys.stdout.write(str(len(ans)) + '\n')
sys.stdout.write(' '.join(map(str, ans)) + '\n')


import os
import sys
from io import BytesIO, IOBase

def dfs(graph, start=0):
	n = len(graph)
	(dp, dp2) = ([False] * n, [False] * n)
	(visited, finished) = ([False] * n, [False] * n)
	ans = []
	stack = [start]
	while stack:
		start = stack[-1]
		if not visited[start]:
			visited[start] = True
			for (child, rp) in graph[start]:
				if not visited[child]:
					stack.append(child)
					if rp == 2:
						dp2[child] = True
		else:
			stack.pop()
			dp[start] = False
			for (child, rp) in graph[start]:
				if finished[child]:
					dp[start] = dp[start] or dp[child]
			finished[start] = True
			if not dp2[start]:
				continue
			if dp[start]:
				continue
			dp[start] = True
			ans.append(start + 1)
	return ans

def main():
	n = int(input())
	e = [[] for _ in range(n)]
	for i in range(n - 1):
		(u, v, t) = map(int, input().split())
		(u, v) = (u - 1, v - 1)
		e[u].append([v, t])
		e[v].append([u, t])
	ans = dfs(e)
	print(len(ans))
	print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import os
import sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd, log
from bisect import *
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
g = lambda : input().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x: reversed(range(x))
mod = int(1000000000.0) + 7
inf = float('inf')
(n,) = gil()
adj = [[] for _ in range(n + 1)]
for _ in range(n - 1):
	(x, y, ti) = gil()
	adj[x].append((y, ti))
	adj[y].append((x, ti))
st = [1]
vis = [0] * (n + 1)
fin = [0] * (n + 1)
cand = [0] * (n + 1)
ans = []
while st:
	if vis[st[-1]]:
		p = st.pop()
		fin[p] = 1
		for (c, ti) in adj[p]:
			if fin[c]:
				if ti > 1:
					cand[p] += 1 if cand[c] == 0 else 0
					if cand[c] == 0:
						ans.append(c)
				cand[p] += cand[c]
	else:
		vis[st[-1]] = 1
		for (c, _) in adj[st[-1]]:
			if vis[c] == 0:
				st.append(c)
print(cand[1])
print(*ans)


n = int(input())
tree = [[] for i in range(n)]
bad_roads = set()
for i in range(n - 1):
	road_input = [int(x) for x in input().split()]
	a = road_input[0] - 1
	b = road_input[1] - 1
	broken = road_input[2] == 2
	tree[a].append(b)
	tree[b].append(a)
	if broken:
		bad_roads.add(a)
		bad_roads.add(b)
s = [(adj_idx, [0], 0) for adj_idx in tree[0]]
while s:
	cur = s.pop()
	to_idx = cur[0]
	parents = cur[1]
	from_idx = cur[2]
	if to_idx in bad_roads:
		bad_roads.difference_update(parents)
		parents = []
	tree[to_idx].remove(from_idx)
	parents.append(to_idx)
	s += [(adj_idx, parents, to_idx) for adj_idx in tree[to_idx]]
candidates = [idx + 1 for idx in bad_roads]
print(len(candidates))
print(' '.join([str(c) for c in candidates]))