There is a binary string $a$ of length $n$. In one operation, you can select any prefix of $a$ with an equal number of $0$ and $1$ symbols. Then all symbols in the prefix are inverted: each $0$ becomes $1$ and each $1$ becomes $0$.

For example, suppose $a=0111010000$.

In the first operation, we can select the prefix of length $8$ since it has four $0$'s and four $1$'s: $[01110100]00\to [10001011]00$.

In the second operation, we can select the prefix of length $2$ since it has one $0$ and one $1$: $[10]00101100\to [01]00101100$.

It is illegal to select the prefix of length $4$ for the third operation, because it has three $0$'s and one $1$.

Can you transform the string $a$ into the string $b$ using some finite number of operations (possibly, none)?


-----Input-----

The first line contains a single integer $t$ ($1\le t\le 10^4$) — the number of test cases.

The first line of each test case contains a single integer $n$ ($1\le n\le 3\cdot 10^5$) — the length of the strings $a$ and $b$.

The following two lines contain strings $a$ and $b$ of length $n$, consisting of symbols $0$ and $1$.

The sum of $n$ across all test cases does not exceed $3\cdot 10^5$.


-----Output-----

For each test case, output "YES" if it is possible to transform $a$ into $b$, or "NO" if it is impossible. You can print each letter in any case (upper or lower).


-----Examples-----

Input
5
10
0111010000
0100101100
4
0000
0000
3
001
000
12
010101010101
100110011010
6
000111
110100
Output
YES
YES
NO
YES
NO


-----Note-----

The first test case is shown in the statement.

In the second test case, we transform $a$ into $b$ by using zero operations.

In the third test case, there is no legal operation, so it is impossible to transform $a$ into $b$.

In the fourth test case, here is one such transformation:

Select the length $2$ prefix to get $100101010101$.

Select the length $12$ prefix to get $011010101010$.

Select the length $8$ prefix to get $100101011010$.

Select the length $4$ prefix to get $011001011010$.

Select the length $6$ prefix to get $100110011010$.

In the fifth test case, the only legal operation is to transform $a$ into $111000$. From there, the only legal operation is to return to the string we started with, so we cannot transform $a$ into $b$.

Source: codeforces | Difficulty: EASY
Tags: Mathematics

Greedy algorithms

Implementation

Constructive algorithms


Solutions:
import sys
import math
inf = float('inf')

def lcm(a, b):
	return int(a / math.gcd(a, b) * b)
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	changed = False
	count_1 = 0
	count_0 = 0
	for i in range(n):
		if a[i] == '1':
			count_1 += 1
		else:
			count_0 += 1
	flag = True
	for i in range(n - 1, -1, -1):
		if changed:
			if a[i] != b[i]:
				pass
			elif count_0 == count_1:
				changed = False
			else:
				flag = False
				break
		elif not changed:
			if a[i] == b[i]:
				pass
			elif count_0 == count_1:
				changed = True
			else:
				flag = False
				break
		if a[i] == '1':
			count_1 -= 1
		else:
			count_0 -= 1
	if flag:
		print('YES')
	else:
		print('NO')


def check(a, ind):
	co = 0
	for i in range(ind + 1):
		if a[i] == '0':
			co += 1
		else:
			co -= 1
	return co
t = int(input())
for T in range(t):
	n = int(input())
	a = list(input())
	b = list(input())
	i = len(a) - 1
	sw = 0
	c = 0
	good = 0
	c = check(a, len(a) - 1)
	while i >= 0:
		if sw == 0:
			if a[i] == b[i]:
				pass
			else:
				sw = 1
				if c == 0:
					pass
				else:
					good = 1
					break
		elif sw == 1:
			if a[i] != b[i]:
				pass
			else:
				sw = 0
				if c == 0:
					pass
				else:
					good = 1
					break
		if a[i] == '0':
			c -= 1
		elif a[i] == '1':
			c += 1
		i -= 1
	if good == 1:
		print('NO')
	else:
		print('YES')


def solve():
	n = int(input())
	s = input()
	t = input()
	sum = 0
	prev = -1
	for i in range(n):
		if s[i] == '0':
			sum += 1
		else:
			sum -= 1
		if sum == 0:
			type = 0
			for j in range(prev + 1, i + 1):
				if s[j] == t[j]:
					if type == -1:
						print('NO')
						return
					type = 1
				else:
					if type == 1:
						print('NO')
						return
					type = -1
			prev = i
	for i in range(prev + 1, n):
		if s[i] != t[i]:
			print('NO')
			return
	print('YES')

def main():
	n = int(input())
	for i in range(n):
		solve()
main()


from functools import reduce
import os
import sys
from collections import *
from decimal import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]

def Ceil(a, b):
	return a // b + int(a % b > 0)
albhabet = 'abcdefghijklmnopqrstuvwxyz'
mo = 1000000007
inf = 1e+18
div = 998244353
for _ in range(inn()):
	n = inn()
	a = input()
	b = input()
	d = defaultdict(int)
	d['0'] = a.count('0')
	d['1'] = a.count('1')
	flag = 0
	ans = 'YES'
	for i in range(n - 1, -1, -1):
		if flag == 0 and a[i] != b[i]:
			if d['0'] != d['1']:
				ans = 'NO'
				break
			else:
				(d['0'], d['1']) = (d['1'], d['0'])
			flag = 1
		elif flag == 1 and a[i] == b[i]:
			if d['0'] != d['1']:
				ans = 'NO'
				break
			else:
				(d['0'], d['1']) = (d['1'], d['0'])
			flag = 0
		d[b[i]] -= 1
	print(ans)


import sys
import math
import random
from queue import PriorityQueue

def get_ints():
	return map(int, input().split())

def palindrome(s):
	mid = len(s) // 2
	for i in range(mid):
		if s[i] != s[len(s) - i - 1]:
			return False
	return True

def solve(a, b, n):
	invflg = 0
	i = n - 1
	inv = [False for i in range(n)]
	count0 = 0
	count1 = 0
	for i in range(n):
		if a[i] == '0':
			count0 += 1
		else:
			count1 += 1
		if count0 == count1:
			inv[i] = True
		else:
			inv[i] = False
	while i >= 0:
		if invflg == 0:
			if a[i] == b[i]:
				i -= 1
			else:
				if inv[i] == False:
					print('NO')
					return
				invflg = 1
				i -= 1
		elif invflg == 1:
			if a[i] != b[i]:
				i -= 1
			else:
				if inv[i] == False:
					print('NO')
					return
				invflg = 0
				i -= 1
	print('YES')
t = int(input())
for tt in range(t):
	n = int(input())
	a = input()
	b = input()
	solve(a, b, n)


import os
import sys
from collections import Counter
from io import BytesIO, IOBase
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')

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a1 = list(input())
		a2 = list(input())
		a1 = list(map(int, a1))
		a2 = list(map(int, a2))
		d = Counter(a1)
		d2 = Counter(a2)
		if a1 == a2:
			print('YES')
		else:
			zeros = Counter()
			ones = Counter()
			if a1[0] == 0:
				zeros[0] = 1
			if a1[0] == 1:
				ones[0] = 1
			for i in range(1, n):
				if a1[i] == 0:
					zeros[i] = zeros[i - 1] + 1
					ones[i] = ones[i - 1]
				else:
					zeros[i] = zeros[i - 1]
					ones[i] = ones[i - 1] + 1
			flag = 0
			f = 0
			for i in range(n - 1, -1, -1):
				if flag == 0:
					x = a1[i]
				if flag == 1:
					x = flag - a1[i]
				if zeros[i] == ones[i]:
					if x != a2[i]:
						if flag == 0:
							flag = 1
						else:
							flag = 0
				elif x != a2[i]:
					print('NO')
					f = 1
					break
			if f == 0:
				print('YES')
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	length = int(input())
	a = input().rstrip()
	b = input().rstrip()
	zero = 0
	one = 0
	avail = set()
	for i in range(length):
		if a[i] == '1':
			one += 1
		else:
			zero += 1
		if zero == one:
			avail.add(i)
	trans = 1
	while length > 0:
		if trans:
			if a[length - 1] != b[length - 1]:
				if length - 1 in avail:
					trans = 0
				else:
					break
			else:
				length -= 1
		elif a[length - 1] == b[length - 1]:
			if length - 1 in avail:
				trans = 1
			else:
				break
		else:
			length -= 1
	if length:
		print('NO')
	else:
		print('YES')


import sys
input = lambda : sys.stdin.readline()
int_arr = lambda : list(map(int, input().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().split())
get_int = lambda : map(int, input().split())
get_flo = lambda : map(float, input().split())
mod = 1000000007

def solve(n, a, b):
	(o, z) = (0, 0)
	for i in range(n):
		if a[i] == '1':
			o += 1
		else:
			z += 1
	flag = 0
	for i in range(n - 1, -1, -1):
		if a[i] != b[i]:
			if flag == 0:
				if o != z:
					print('NO')
					return
				flag = 1
		elif flag == 1:
			if o != z:
				print('NO')
				return
			flag = 0
		if flag == 0:
			if a[i] == '1':
				o -= 1
			else:
				z -= 1
		elif a[i] == '1':
			z -= 1
		else:
			o -= 1
	else:
		print('YES')
for _ in range(int(input())):
	n = int(input())
	a = str(input())[:-1]
	b = str(input())[:-1]
	solve(n, a, b)


def solve():
	n = int(input())
	a = input()
	b = input()
	c1 = 0
	c2 = 0
	f = 0
	for i in range(n):
		if a[i] == '1':
			c1 += 1
		else:
			c2 += 1
	for i in range(n - 1, -1, -1):
		if a[i] != b[i]:
			if f == 0:
				if c1 != c2:
					print('NO')
					return
				f = 1
		elif f == 1:
			if c1 != c2:
				print('NO')
				return
			f = 0
		if f == 0:
			if a[i] == '1':
				c1 -= 1
			else:
				c2 -= 1
		elif a[i] == '1':
			c2 -= 1
		else:
			c1 -= 1
	print('YES')
t = int(input())
while t:
	solve()
	t -= 1


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

def input():
	return sys.stdin.readline()[:-1]
YES = 'YES'
NO = 'NO'

def solve(N, A, B):
	(T_A0, T_A1, T_B0, T_B1) = ([], [], [], [])
	(n_A0, n_A1, n_B0, n_B1) = (0, 0, 0, 0)
	for i in range(N):
		if A[i] == '0':
			n_A0 += 1
		else:
			n_A1 += 1
		T_A0.append(n_A0)
		T_A1.append(n_A1)
		if B[i] == '0':
			n_B0 += 1
		else:
			n_B1 += 1
		T_B0.append(n_B0)
		T_B1.append(n_B1)
	flag = True
	for i in reversed(range(N)):
		if flag and A[i] != B[i]:
			flag = False
			if T_A0[i] != T_A1[i] or T_B0[i] != T_B1[i]:
				return False
		elif not flag and A[i] == B[i]:
			flag = True
			if T_A0[i] != T_A1[i] or T_B0[i] != T_B1[i]:
				return False
	return True

def main():
	T0 = int(input())
	for _ in range(T0):
		N = int(input())
		A = input()
		B = input()
		ans = solve(N, A, B)
		if ans:
			print('YES')
		else:
			print('NO')
main()


rr = input
rri = lambda : int(rr())
rrm = lambda : list(map(int, rr().split()))
T = rri()

def solve():
	n = rri()
	a = input()
	b = input()
	dpequal = []
	if a == b:
		return 'YES'
	if n % 2 == 1:
		if a[-1] != b[-1]:
			return 'NO'
		else:
			n -= 1
	if a[0] == '1':
		dp = [1]
	else:
		dp = [-1]
	for i in range(0, n, 2):
		aa = a[i:i + 2]
		bb = b[i:i + 2]
		aam = max(aa.count('0'), aa.count('1'))
		bbm = max(bb.count('0'), bb.count('1'))
		dpequal.append(int(aa == bb))
		if aam != bbm:
			return 'NO'
	for i in range(1, n):
		if a[i] == '1':
			temp = 1
		else:
			temp = -1
		dp.append(dp[-1] + temp)
	dpsum = []
	for i in range(1, n, 2):
		dpsum.append(int(dp[i] == 0))
	if dpsum.count(1) == 0:
		return 'NO'
	tempi = ''.join(map(str, dpsum)).rindex('1')
	for i in range(tempi + 1, len(dpequal)):
		if dpequal[i] != 1:
			return 'NO'
	i = 0
	while i <= tempi:
		if dpsum[i] == 0:
			start = i
			while dpsum[i] != 1:
				i += 1
				continue
			temp = dpequal[start:i + 1]
			if temp.count(temp[0]) != len(temp):
				return 'NO'
			i += 1
		else:
			i += 1
	return 'YES'
for t in range(T):
	print(solve())


t = int(input())
for _ in range(t):
	n = int(input())
	real = input()
	final = input()
	flipped_real = real
	flipped_real = flipped_real.replace('1', '2')
	flipped_real = flipped_real.replace('0', '1')
	flipped_real = flipped_real.replace('2', '0')
	count = 0
	i = 0
	last = -1
	temp = []
	for char in real:
		if char == '0':
			count += 1
		else:
			count -= 1
		if count == 0:
			last = i
			temp.append(i)
		i += 1
	if real[last + 1:] != final[last + 1:]:
		print('NO')
		continue
	flag = 0
	start = 0
	for i in range(len(temp)):
		end = temp[i] + 1
		if real[start:end] != final[start:end] and flipped_real[start:end] != final[start:end]:
			print('NO')
			flag = 1
			break
		start = end
	if flag == 0:
		print('YES')


k = int(input())
for i in range(k):
	n = int(input())
	a = input()
	b = input()
	(zeros, ones) = (a.count('0'), a.count('1'))
	swapped = False
	i = n - 1
	while i > -1:
		if a[i] == b[i] and (not swapped) or (a[i] != b[i] and swapped):
			if a[i] == '0':
				zeros -= 1
			else:
				ones -= 1
			i -= 1
		elif zeros == ones:
			swapped = not swapped
		else:
			break
	print('NO' if i != -1 else 'YES')


for _ in range(int(input())):
	k = int(input())
	a = str(input())
	b = str(input())
	l = [0] * len(a)
	o = 0
	z = 0
	for i in range(len(a)):
		if a[i] == '1':
			o += 1
		else:
			z += 1
		if o == z:
			l[i] = 1
	i = len(a) - 1
	tem = True
	while i >= 0:
		if a[i] == b[i]:
			while i >= 0 and a[i] == b[i]:
				i = i - 1
			if i >= 0 and l[i] == 0:
				print('NO')
				tem = False
				break
		else:
			if i >= 0 and l[i] == 0:
				print('NO')
				tem = False
				break
			while i >= 0 and a[i] != b[i]:
				i = i - 1
			if i >= 0 and l[i] == 0:
				print('NO')
				tem = False
				break
	if tem:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	s1 = input()
	s2 = input()
	end = [False for _ in range(n)]
	(a, b) = (0, 0)
	for k in range(n):
		if s1[k] == '0':
			a += 1
		else:
			b += 1
		if a == b:
			end[k] = True
	found = False
	reverse = False
	for k in range(n - 1, -1, -1):
		if reverse == False:
			if s1[k] == s2[k]:
				pass
			elif end[k]:
				reverse = True
			else:
				found = True
				break
		elif f'{1 - int(s1[k])}' == s2[k]:
			pass
		elif end[k]:
			reverse = False
		else:
			found = True
			break
	if found:
		print('NO')
	else:
		print('YES')


def solve(arr, brr):
	N = len(arr)
	(xA, xB) = (0, 0)
	iLast = -1
	cur = []
	for (i, (a, b)) in enumerate(zip(arr, brr)):
		if xA == 0:
			h = a ^ b
		cur.append(a ^ b ^ h)
		xA += 1 if a else -1
		xB += 1 if b else -1
		if not xA or not xB:
			if xA or xB or any(cur):
				return 'NO'
			cur.clear()
			iLast = i
	for i in range(iLast + 1, N):
		if arr[i] != brr[i]:
			return 'NO'
	return 'YES'
for _ in range(int(input())):
	input()
	arr = list(map(int, list(input())))
	brr = list(map(int, list(input())))
	print(solve(arr, brr))


def equivalent(prefix1, prefix2):
	num1 = int(prefix1, 2)
	num2 = int(prefix2, 2)
	return num1 == num2 or 2 ** len(prefix1) - 1 ^ num1 == num2
tests = int(input())
for k in range(tests):
	length = int(input())
	num1 = input()
	num2 = input()
	last = 0
	ones = 0
	zeroes = 0
	for k in range(length):
		if num1[k] == '1':
			ones += 1
		else:
			zeroes += 1
		if ones == zeroes:
			if not equivalent(num1[last:k + 1], num2[last:k + 1]):
				break
			last = k + 1
	if num1[last:] == num2[last:]:
		print('YES')
	else:
		print('NO')


def match(n, a, b):
	count = 0
	a += '0'
	b += '0'
	for i in range(n):
		count += 2 * (ord(a[i]) - ord('0')) - 1
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and count != 0:
			return False
	return True
t = int(input())
for i in range(t):
	print('YES' if match(int(input()), input(), input()) else 'NO')


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	if a == b:
		print('YES')
		continue
	f = 0
	if a[0] == b[0]:
		f = 1
	else:
		f = 0
	z = {'0': 1, '1': -1}
	c = z[a[0]]
	xf = 0
	for i in range(1, n):
		if f == 0 and a[i] == b[i]:
			if c != 0:
				xf = 1
				print('NO')
				break
			f = 1
		elif f == 1 and a[i] != b[i]:
			if c != 0:
				xf = 1
				print('NO')
				break
			f = 0
		c += z[a[i]]
	if xf == 0:
		if f == 0:
			if c != 0:
				print('NO')
			else:
				print('YES')
		else:
			print('YES')


import sys, os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	if n == 1:
		if a == b:
			print('YES')
		else:
			print('NO')
	elif a == b:
		print('YES')
	else:
		prefix = []
		one = 0
		for i in range(n):
			if a[i] == '1':
				one += 1
			else:
				one -= 1
			prefix.append(one)
		flag = True
		count = 0
		for i in range(n - 1, -1, -1):
			if a[i] != b[i]:
				if count % 2 == 1:
					continue
				elif prefix[i] == 0:
					count += 1
				else:
					flag = False
					break
			elif count % 2 != 0:
				if prefix[i] == 0:
					count += 1
				else:
					flag = False
					break
		if flag:
			print('YES')
		else:
			print('NO')


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	cnt = []
	ini = 0
	if a == b:
		print('YES')
		continue
	for j in range(n):
		if a[j] == '0':
			ini += 1
		cnt += [ini]
	if a[-1] != b[-1]:
		bool = False
		x = cnt[-1]
		y = n - cnt[-1]
		if x != y:
			print('NO')
			continue
	else:
		bool = True
	bool1 = True
	for k in range(n - 1, -1, -1):
		if bool == True and a[k] == b[k]:
			continue
		elif bool == True and a[k] != b[k]:
			bool = False
			x = cnt[k]
			y = k + 1 - x
			if y != x:
				print('NO')
				bool1 = False
				break
		elif bool == False and a[k] == b[k]:
			bool = True
			x = cnt[k]
			y = k + 1 - x
			if y != x:
				print('NO')
				bool1 = False
				break
	if bool1 == False:
		continue
	else:
		print('YES')
		continue


import math
from collections import defaultdict, Counter, deque
from heapq import heapify, heappush, heappop

def solve():
	n = int(input())
	a = list(input())
	b = list(input())
	pre = [0 for i in range(n)]
	o = z = 0
	for i in range(n):
		if a[i] == '0':
			z += 1
		else:
			o += 1
		if o == z:
			pre[i] = 1
	inverted = 0
	for i in range(n - 1, -1, -1):
		if inverted:
			a[i] = '1' if a[i] == '0' else '0'
		if a[i] != b[i]:
			if pre[i]:
				inverted ^= 1
			else:
				print('NO')
				return
	print('YES')
t = 1
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def st():
	return input().rstrip('\n')

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

def ma():
	return map(int, input().split())
t = inp()
while t:
	t -= 1
	n = inp()
	a = st()
	b = st()
	li = []
	fl = 0
	(ac, bc) = (0, 0)
	fl = 0
	li = []
	for i in range(n):
		if a[i] == b[i]:
			if ac or bc:
				li.append(i - 1)
				if ac != bc:
					fl = 1
					break
				(ac, bc) = (0, 0)
			continue
		elif a[i] == '1':
			ac += 1
		else:
			bc += 1
	if ac or bc:
		if ac != bc:
			fl = 1
		li.append(n - 1)
	co = [0]
	for i in a:
		if i == '1':
			co.append(co[-1] + 1)
		else:
			co.append(co[-1])
	for i in range(len(li) - 1, -1, -1):
		z = li[i]
		cone = co[z + 1]
		czero = z + 1 - cone
		if cone != czero:
			fl = 1
			break
	if fl:
		print('NO')
	else:
		print('YES')


T = int(input())
for _ in range(T):
	n = int(input())
	s1 = input()
	s2 = input()
	one = [0]
	zero = [0]
	for i in range(n):
		if s1[i] == '1':
			one.append(one[-1] + 1)
			zero.append(zero[-1])
		else:
			zero.append(zero[-1] + 1)
			one.append(one[-1])
	one = one[1:]
	zero = zero[1:]
	cnt = 0
	flag = True
	for i in range(n - 1, -1, -1):
		a = s1[i]
		if cnt % 2 == 1:
			a = str(int(a) ^ 1)
		if a != s2[i] and zero[i] != one[i]:
			flag = False
			break
		elif a != s2[i]:
			cnt += 1
	if flag:
		print('YES')
	else:
		print('NO')


for i in range(int(input())):
	n = int(input())
	a = input()
	req = input()
	d = {'0': 0, '1': 0}
	for i in range(n):
		d[a[i]] += 1
	i = n - 1
	diff = 0
	f = 0
	while i >= 0:
		if a[i] == req[i]:
			if diff == 0:
				d[a[i]] -= 1
			else:
				if d['0'] == d['1']:
					if diff == 1:
						diff = 0
					else:
						diff = 1
				else:
					f = 1
					break
				d[a[i]] -= 1
		elif diff == 0:
			if d['0'] == d['1']:
				diff = 1
			else:
				f = 1
				break
			d[a[i]] -= 1
		else:
			d[a[i]] -= 1
		i -= 1
	if f == 1:
		print('NO')
	else:
		print('YES')


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	a = a + ' '
	b = b + ' '
	count = prefix = x = 0
	for j in range(n):
		if a[j] == '1':
			x = x + 1
		else:
			x = x - 1
		count = x
		if (a[j] == b[j]) != (a[j + 1] == b[j + 1]) and count != 0:
			prefix = 1
			break
	if prefix == 1:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	s = input()
	t = input()
	coun0 = 0
	coun1 = 0
	f = -1
	f2 = 0
	for i in range(n):
		if s[i] == '0':
			coun0 += 1
		else:
			coun1 += 1
		if s[i] == t[i] and (f == -1 or f == 0):
			f = 0
		elif s[i] != t[i] and (f == -1 or f == 1):
			f = 1
		else:
			f2 = 1
			break
		if coun0 == coun1:
			f = -1
	if f2 == 0 and (f == -1 or f == 0):
		print('YES')
	else:
		print('NO')


t = int(input())
for _ in range(t):

	def main():
		n = int(input())
		(a, b) = (input(), input())
		swap = 0
		prefix = []
		cur = 0
		for i in range(n):
			if a[i] == '1':
				cur += 1
			prefix.append(cur)
		for i in range(n - 1, -1, -1):
			if swap:
				if a[i] == b[i]:
					if prefix[i] * 2 == i + 1:
						swap = 0
					else:
						return print('NO')
			elif a[i] != b[i]:
				if prefix[i] * 2 == i + 1:
					swap = 1
				else:
					return print('NO')
		return print('YES')
	main()


for t in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	a0 = a.count('0')
	b0 = b.count('0')
	if a == b:
		print('YES')
	elif a0 != b0:
		print('NO')
	else:
		c0 = a0
		m = n
		mo = 0
		for i in range(n - 1, -1, -1):
			if m == 2 * c0:
				mo = 1
			if mo == 0 and a[i] != b[i]:
				print('NO')
				break
			elif mo == 1:
				if a[i] == b[i]:
					mo = 2
				else:
					mo = 3
			elif mo == 2 and a[i] != b[i] or (mo == 3 and a[i] == b[i]):
				print('NO')
				break
			if a[i] == '0':
				c0 -= 1
			m -= 1
		else:
			print('YES')


def check(s, s_n):
	good = [False for _ in range(len(s))]
	c0 = 0
	c1 = 0
	for i in range(len(s)):
		if i > 0 and s[i] == s_n[i] and (s[i - 1] != s_n[i - 1]):
			if not good[i - 1]:
				return False
		if i > 0 and s[i] != s_n[i] and (s[i - 1] == s_n[i - 1]):
			if not good[i - 1]:
				return False
		if s[i] == '1':
			c1 += 1
		else:
			c0 += 1
		if c1 == c0:
			good[i] = True
	if s[-1] != s_n[-1]:
		return good[-1]
	return True
n = int(input())
for _ in range(n):
	input()
	s = input()
	s_n = input()
	if check(s, s_n):
		print('YES')
	else:
		print('NO')


def rev_st(st):
	return ['1' if i == '0' else '0' for i in st]

def func():
	i = 0
	count_0 = 0
	count_1 = 0
	flag = True
	while i < n:
		if a[i] == b[i]:
			if a[i] == '1':
				count_1 += 1
			else:
				count_0 += 1
			i += 1
		else:
			if count_0 == count_1:
				pass
			else:
				flag = False
				break
			while i < n and a[i] != b[i]:
				if a[i] == '1':
					count_1 += 1
				else:
					count_0 += 1
				i += 1
			if count_0 == count_1:
				pass
			else:
				flag = False
				break
	if flag:
		print('YES')
	else:
		print('NO')
for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	func()


n = int(input())
data = []
for _ in range(n):
	l = int(input())
	a = input()
	b = input()
	data.append((l, a, b))

def func(dp):
	x = dp[0]
	a = list(dp[1][::-1])
	b = list(dp[2][::-1])
	ones_in_a = 0
	for i in range(x):
		if a[i] == '1':
			ones_in_a += 1
	zeroes_in_a = x - ones_in_a
	no_times_operation_done = 0
	for i in range(x):
		if no_times_operation_done % 2 != 0:
			if a[i] == '1':
				a[i] = '0'
			else:
				a[i] = '1'
		if a[i] != b[i] and zeroes_in_a == ones_in_a:
			no_times_operation_done += 1
			if a[i] == '1':
				zeroes_in_a -= 1
				a[i] = '0'
			else:
				ones_in_a -= 1
				a[i] = '1'
		elif a[i] == '1':
			ones_in_a -= 1
		else:
			zeroes_in_a -= 1
	if a == b:
		print('YES')
	else:
		print('NO')
for data_point in data:
	func(data_point)


def nnot(s):
	q = s.replace('0', '#')
	q = q.replace('1', '0')
	return q.replace('#', '1')

def check(s1, s2):
	return s1 == s2 or s1 == nnot(s2)

def solve(n, a, b):
	(c1, c0) = (0, 0)
	al = []
	for i in range(n):
		ch = a[i]
		if ch == '0':
			c0 += 1
		else:
			c1 += 1
		if c1 == c0:
			al.append(i)
	(ll, pp) = (0, 0)
	for i in al:
		pp = i + 1
		if not check(a[ll:pp], b[ll:pp]):
			return 'NO'
		ll = pp
	if a[pp:] == b[pp:]:
		return 'YES'
	return 'NO'
tc = int(input())
for _ in range(tc):
	n = int(input())
	a = input()
	b = input()
	print(solve(n, a, b))


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	j = n - 1
	while j >= 0 and a[j] == b[j]:
		j -= 1
	if j < 0:
		print('YES')
	else:
		one = a[:j + 1].count('1')
		zero = a[:j + 1].count('0')
		flag = 1
		ans = 1
		while j >= 0:
			if flag == 1:
				if one == zero:
					while j >= 0 and a[j] != b[j]:
						if a[j] == '1':
							one -= 1
						else:
							zero -= 1
						j -= 1
				else:
					ans = 0
					print('NO')
					break
				if j >= 0:
					flag = 0
			if flag == 0:
				if one == zero:
					while j >= 0 and a[j] == b[j]:
						if a[j] == '1':
							one -= 1
						else:
							zero -= 1
						j -= 1
				else:
					ans = 0
					print('NO')
					break
				if j >= 0:
					flag = 1
		if ans == 1:
			print('YES')


def calc():
	n = int(input())
	a = input()
	b = input()
	dp0 = [0] * n
	dp1 = [0] * n
	if a[0] == '0':
		dp0[0] = 1
		dp1[0] = 0
	else:
		dp0[0] = 0
		dp1[0] = 1
	for i in range(1, n):
		if a[i] == '0':
			dp0[i] = dp0[i - 1] + 1
			dp1[i] = dp1[i - 1]
		else:
			dp0[i] = dp0[i - 1]
			dp1[i] = dp1[i - 1] + 1
	flip = False
	for i in range(n):
		j = -i - 1
		if not flip:
			if a[j] != b[j]:
				if dp0[j] == dp1[j]:
					flip = True
				else:
					print('NO')
					return
		elif a[j] == b[j]:
			if dp0[j] == dp1[j]:
				flip = False
			else:
				print('NO')
				return
	print('YES')
t = int(input())
for k in range(t):
	calc()


a = '010101010101'
b = '100110011010'

def answer(a, b):
	a = a + '0'
	b = b + '0'
	count = prefix = x = 0
	for i in range(len(a) - 1):
		if a[i] == '1':
			x += 1
		elif a[i] == '0':
			x -= 1
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and x != 0:
			return 'NO'
	return 'YES'
t = int(input())
for w in range(t):
	n = int(input())
	a = input()
	b = input()
	print(answer(a, b))


def func(n, a, b):
	aone = a.count('1')
	bone = b.count('1')
	if aone != bone:
		print('NO')
		return ''
	arr = [-1 for x in range(n)]
	one = 0
	zero = 0
	for i in range(n):
		if a[i] == '0':
			zero += 1
		elif a[i] == '1':
			one += 1
		arr[i] = 1 if zero == one else 0
	flag = 0
	for i in range(n - 1, -1, -1):
		if flag == 0:
			if a[i] != b[i] and arr[i] != 1:
				print('NO')
				return ''
			elif a[i] == b[i]:
				pass
			elif a[i] != b[i] and arr[i] == 1:
				flag = 1
		elif flag == 1:
			if a[i] == b[i] and arr[i] != 1:
				print('NO')
				return ''
			elif a[i] != b[i]:
				pass
			elif a[i] == b[i] and arr[i] == 1:
				flag = 0
	print('YES')
	return ''
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	func(n, a, b)


import sys, math

def compute(l, a, b):
	(a_c, b_c) = (sum(a), sum(b))
	swap_a = 0
	for i in range(l)[::-1]:
		if a[i] ^ swap_a != b[i]:
			if a_c != b_c:
				return 'NO'
			swap_a ^= 1
			a_c = i - a_c + 1
		a_c -= a[i] ^ swap_a
		b_c -= b[i]
	return 'YES'
for _ in '_' * int(input()):
	print(compute(int(input()), [*map(int, input())], [*map(int, input())]))


for _ in range(int(input())):
	input()
	n = input()
	m = input()
	(f, n1, n0) = (0, n.count('1'), n.count('0'))
	for i in range(len(n) - 1, -1, -1):
		if int(n[i]) ^ f != int(m[i]):
			if n1 != n0:
				print('NO')
				break
			f = 1 - f
		n1 -= n[i] == '1'
		n0 -= n[i] == '0'
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input().strip()
	b = input().strip()
	if n & 1 and (not a[-1] == b[-1]):
		print('NO')
		continue
	(one, zero) = (0, 0)
	(lpre, lsame, f) = (True, True, True)
	for k in range(n >> 1):
		f = True
		i = 2 * k
		j = i + 1
		one += int(a[i]) + int(a[j])
		zero += int(a[i] == '0') + int(a[j] == '0')
		(x, y) = (a[i] == b[i], a[j] == b[j])
		if not x == y:
			f = False
			break
		if lpre:
			lsame = x
		elif not lsame == x:
			f = False
			break
		lpre = one == zero
		if not x:
			f = lpre
	print('YNEOS'[int(not f)::2])


from sys import stdin, stdout
t = int(stdin.readline().rstrip())
for _ in range(t):
	n = int(stdin.readline().rstrip())
	a = [int(x) for x in list(stdin.readline().rstrip())]
	b = [int(x) for x in list(stdin.readline().rstrip())]
	aSumVal = 0
	aSums = [False] * n
	for ii in range(n):
		aSumVal += a[ii]
		aSums[ii] = aSumVal * 2 == ii + 1
	isEqual = [a[ii] == b[ii] for ii in range(n)]
	switching = False
	doable = True
	for ii in range(n - 1, -1, -1):
		if aSums[ii]:
			if not switching and (not isEqual[ii]):
				switching = True
			elif switching and isEqual[ii]:
				switching = False
		elif not switching and (not isEqual[ii]) or (switching and isEqual[ii]):
			doable = False
			break
	if doable:
		print('YES')
	else:
		print('NO')


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt, log2
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
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')

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

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 testcase(t):
	for pp in range(t):
		solve(pp)

def google(p):
	print('Case #' + str(p) + ': ', end='')

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

def modInverse(b):
	g = gcd(b, mod)
	if g != 1:
		return -1
	else:
		return pow(b, mod - 2, mod)

def power(x, y, p):
	y %= p - 1
	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

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

def solve(case):
	n = int(inp())
	a = list(inp())
	b = list(inp())
	for i in range(n):
		a[i] = int(a[i])
		b[i] = int(b[i])
	pre0 = [0] * (n + 1)
	pre1 = [0] * (n + 1)
	for i in range(n):
		if a[i] == 0:
			pre0[i] = pre0[i - 1] + 1
		else:
			pre0[i] = pre0[i - 1]
		if a[i] == 1:
			pre1[i] = pre1[i - 1] + 1
		else:
			pre1[i] = pre1[i - 1]
	ind = []
	for i in range(n):
		if pre1[i] == pre0[i]:
			ind.append(i)
	prev = 0
	for i in ind:
		opp = True
		for j in range(prev, i + 1):
			if a[j] == b[j]:
				opp = False
		same = True
		for j in range(prev, i + 1):
			if a[j] != b[j]:
				same = False
		if not opp and (not same):
			print('NO')
			return
		prev = i + 1
	if prev != n:
		opp = True
		same = True
		for j in range(prev, n):
			if a[j] == b[j]:
				opp = False
			if a[j] != b[j]:
				same = False
		if not same:
			print('NO')
			return
	print('YES')
testcase(int(inp()))


import sys

def can_obtain(src, tgt):
	assert len(src) == len(tgt)
	n = len(src)
	can_swap = [False] * n
	counts = [0] * 2
	for idx in range(n):
		counts[src[idx]] += 1
		can_swap[idx] = counts[0] == counts[1]
	parity = 0
	for idx in range(n - 1, -1, -1):
		if src[idx] ^ parity != tgt[idx]:
			if can_swap[idx]:
				parity ^= 1
			else:
				return False
	return True

def read_num():
	return list(map(int, sys.stdin.readline().strip()))
test_count = int(sys.stdin.readline().strip())
for _ in range(test_count):
	_ = sys.stdin.readline()
	(src, tgt) = (read_num(), read_num())
	print('YES' if can_obtain(src, tgt) else 'NO')


def chck(a1, a2, b1, idx, a, b, n):
	s1 = []
	s2 = []
	s3 = []
	z = o = 0
	ind = 0
	for i in range(n):
		ai = a[i]
		s1.append(ai)
		s2.append(1 - ai)
		s3.append(b[i])
		if ai == 0:
			z += 1
		else:
			o += 1
		if z == o:
			a1.append(s1)
			a2.append(s2)
			b1.append(s3)
			idx.append(i)
			s1 = []
			s2 = []
			s3 = []
			ind += 1
	return ind
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input()]
	b = [int(x) for x in input()]
	a1 = []
	a2 = []
	b1 = []
	idx = []
	ind = chck(a1, a2, b1, idx, a, b, n)
	m = 0
	p = -1
	for i in range(ind):
		p = idx[i] - p
		for x in range(p):
			if a1[i][x] != b1[i][x]:
				m = 1
				break
		if m == 1:
			m = 0
			for x in range(p):
				if a2[i][x] != b1[i][x]:
					m = 1
					break
		if m == 1:
			break
		p = idx[i]
	if m == 0:
		for i in range(p + 1, n):
			if a[i] != b[i]:
				m = 1
				break
	if m == 0:
		print('YES')
	else:
		print('NO')


for _ in range(int(input())):
	n = int(input())
	string = input()
	req = input()
	array = []
	one = 0
	zero = 0
	for i in string:
		if i == '0':
			zero += 1
		else:
			one += 1
		if one == zero:
			array.append(True)
		else:
			array.append(False)
	invert = 0
	for i in range(n - 1, -1, -1):
		if not invert and req[i] == string[i]:
			pass
		elif not invert and req[i] != string[i]:
			if array[i]:
				invert = 1
			else:
				print('NO')
				break
		elif invert and req[i] != str(1 - int(string[i])):
			if not array[i]:
				print('NO')
				break
			invert = 0
	else:
		print('YES')


t = int(input())
for i in range(t):
	n = int(input())
	arr1 = input()
	s1 = [int(j) for j in arr1]
	s1.append(1)
	arr2 = input()
	s2 = [int(j) for j in arr2]
	s2.append(1)
	cnt = 0
	j = 0
	flag = 0
	while j + 1 < len(s1) and flag == 0:
		cnta = 0
		cntb = 0
		if s1[j] == s2[j]:
			if s1[j] == 0:
				cnta += 1
			else:
				cntb += 1
			for j in range(j + 1, len(s1)):
				if s1[j] != s2[j]:
					if cnta == cntb:
						cnt += 1
						break
					else:
						flag = 1
						break
				if s1[j] == 0:
					cnta += 1
				else:
					cntb += 1
		else:
			if s1[j] == 0:
				cnta += 1
			else:
				cntb += 1
			for j in range(j + 1, len(s1)):
				if s1[j] == s2[j]:
					if cnta == cntb:
						cnt += 1
						break
					else:
						flag = 1
						break
				if s1[j] == 0:
					cnta += 1
				else:
					cntb += 1
	if flag == 0:
		print('YES')
	else:
		print('NO')


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
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))

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

def lcm(a, b):
	return a * b / gcd(a, b)
mod = int(1000000000.0) + 7

def power(k, n):
	if n == 0:
		return 1
	if n % 2:
		return power(k, n - 1) * k % mod
	t = power(k, n // 2)
	return t * t % mod

def totalPrimeFactors(n):
	count = 0
	if n % 2 == 0:
		count += 1
		while n % 2 == 0:
			n //= 2
	i = 3
	while i * i <= n:
		if n % i == 0:
			count += 1
			while n % i == 0:
				n //= i
		i += 2
	if n > 2:
		count += 1
	return count

def main():
	for _ in range(int(input())):
		n = int(input())
		A = input()
		B = input()
		a = []
		b = []
		for i in A:
			if i == '1' or i == '0':
				a.append(int(i))
		for i in B:
			if i == '1' or i == '0':
				b.append(int(i))
		f = 0
		o = sum(a)
		z = n - o
		pos = 1
		for i in range(n - 1, -1, -1):
			if a[i] ^ f != b[i]:
				if z != o:
					pos = 0
				else:
					f ^= 1
			if a[i]:
				o -= 1
			else:
				z -= 1
		if pos:
			print('YES')
		else:
			print('NO')
	return
main()


for p in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	a += '0'
	b += '0'
	(f, p) = (0, 0)
	for i in range(n):
		if a[i] == '1':
			x = 1
		else:
			x = 0
		if a[i] == '0':
			y = 1
		else:
			y = 0
		f += x - y
		if a[i] == b[i]:
			w = 1
		else:
			w = 0
		if a[i + 1] == b[i + 1]:
			z = 1
		else:
			z = 0
		if w != z and f != 0:
			p = 1
			print('NO')
			break
	if not p:
		print('YES')


def solve(A, B):
	count0 = 0
	count1 = 0
	for a in A:
		if a == 1:
			count1 += 1
		else:
			count0 += 1
	flag = 0
	for i in reversed(range(len(A))):
		if flag == 0:
			if A[i] != B[i]:
				if count0 != count1:
					return 'NO'
				(count0, count1) = (count1, count0)
				flag = 1
		elif flag == 1:
			if A[i] == B[i]:
				if count0 != count1:
					return 'NO'
				(count0, count1) = (count1, count0)
				flag = 0
		if A[i] == flag:
			count0 -= 1
		else:
			count1 -= 1
	return 'YES'
x = int(input())
for _ in range(x):
	a = int(input())
	A = list(map(int, input()))
	B = list(map(int, input()))
	print(solve(A, B))


import sys
T = int(input())

def invert(s):
	a = ''
	for i in s:
		a += '0' if i == '1' else '1'
	return a

def determine(a, b):
	n = len(a)
	if n % 2:
		if not a[-1] == b[-1]:
			return 'NO'
	lastBalance = -1
	bba = 0
	bbb = 0
	for i in range(n):
		bba += 1 if a[i] == '0' else -1
		bbb += 1 if b[i] == '0' else -1
		if bba == 0 or bbb == 0:
			if not bba == bbb:
				return 'NO'
			aa = a[lastBalance + 1:i + 1]
			bb = b[lastBalance + 1:i + 1]
			if not (aa == bb or aa == invert(bb)):
				return 'NO'
			lastBalance = i
	aa = a[lastBalance + 1:]
	bb = b[lastBalance + 1:]
	if not aa == bb:
		return 'NO'
	return 'YES'
for t in range(T):
	input()
	a = input()
	b = input()
	print(determine(a, b))


answers = []

def solve(n, a, b):
	if a == b:
		answers.append('YES')
		return
	zeroA = 0
	oneA = 0
	zeroB = 0
	oneB = 0
	for ele in a:
		if ele == '0':
			zeroA += 1
		else:
			oneA += 1
	for ele in b:
		if ele == '0':
			zeroB += 1
		else:
			oneB += 1
	if zeroB != zeroA:
		answers.append('NO')
		return
	store = {}
	count0 = 0
	count1 = 0
	for (i, ele) in enumerate(a):
		if ele == '0':
			count0 += 1
		else:
			count1 += 1
		if count1 == count0:
			store[i] = 1
	flipped = 0
	for i in range(n - 1, -1, -1):
		if flipped == 0:
			if b[i] == a[i]:
				continue
			if i not in store:
				answers.append('NO')
				return
			flipped = 1
		else:
			if b[i] != a[i]:
				continue
			if i not in store:
				answers.append('NO')
				return
			flipped = 0
	answers.append('YES')
T = int(input())
while T:
	n = int(input())
	a = input()
	b = input()
	solve(n, a, b)
	T -= 1
for ans in answers:
	print(ans)


from collections import deque, defaultdict
from math import sqrt, ceil, factorial, floor, inf, log2, sqrt, gcd
import bisect
import sys
import copy

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

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	n = int(input())
	s1 = input()
	s2 = input()
	zeros = [0] * n
	ones = [0] * n
	if s1[0] == '0':
		zeros[0] += 1
	else:
		ones[0] += 1
	for i in range(1, n):
		if s1[i] == '0':
			zeros[i] += 1
		else:
			ones[i] += 1
		zeros[i] += zeros[i - 1]
		ones[i] += ones[i - 1]
	arr = set()
	for i in range(n):
		if zeros[i] == ones[i]:
			arr.add(i)
	ind = 1
	flag = 0
	for i in range(len(s1) - 1, -1, -1):
		if ind == -1:
			if s1[i] != s2[i]:
				continue
			if s1[i] == s2[i] and i in arr:
				ind = -ind
			else:
				flag = 1
				break
		elif s1[i] == s2[i]:
			continue
		elif i in arr:
			ind = -ind
		else:
			flag = 1
			break
	if flag == 1:
		print('NO')
	else:
		print('YES')


def f(l, a, b):
	crnt = 0
	odd = [0] * l
	table = [False] * l
	s = 0
	for i in range(l):
		if a[i] != b[i]:
			odd[i] = 1
		t = 1 if a[i] == '1' else -1
		s += t
		if s == 0:
			table[i] = True
	for i in range(l - 1, -1, -1):
		if odd[i] == crnt:
			continue
		elif table[i]:
			crnt = 1 - crnt
		else:
			print('NO')
			break
	else:
		print('YES')
n = int(input())
for _ in range(n):
	l = int(input())
	a = input()
	b = input()
	f(l, a, b)


testcases = int(input())
while testcases > 0:
	n = int(input())
	a = input()
	b = input()
	zeroCount = 0
	oneCount = 0
	for i in range(len(a)):
		if a[i] == '0':
			zeroCount += 1
		else:
			oneCount += 1
	if a == b:
		print('YES')
	else:
		flag = 0
		i = n - 1
		change = False
		while i >= 0:
			if a[i] != b[i] and change == False or (a[i] == b[i] and change == True):
				if zeroCount == oneCount:
					if change == False:
						change = True
					else:
						change = False
				else:
					flag = 1
					break
			if a[i] == '1':
				oneCount -= 1
			else:
				zeroCount -= 1
			i -= 1
		if flag == 1:
			print('NO')
		else:
			print('YES')
	testcases -= 1


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	if a == b:
		print('YES')
		continue
	s = ''
	one = 0
	zero = 0
	j = 0
	flag = True
	for i in range(n):
		if a[i] == '1':
			one += 1
			s += '0'
		else:
			zero += 1
			s += '1'
		if one == zero:
			if s[j:i + 1] != b[j:i + 1] and a[j:i + 1] != b[j:i + 1]:
				print('NO')
				flag = False
				break
			j = i + 1
	if flag == True:
		if a[j:] == b[j:]:
			print('YES')
		else:
			print('NO')


def fun(a, b, n):
	a_s = []
	b_s = []
	one = 0
	zero = 0
	ind = 0
	for j in range(n):
		if a[j] == '0':
			zero += 1
		else:
			one += 1
		if one == zero:
			a_s.append(a[ind:j + 1])
			b_s.append(b[ind:j + 1])
			ind = j + 1
	for j in range(len(a_s)):
		if a_s[j][0] == b_s[j][0]:
			continue
		else:
			s = ''
			for k in range(len(a_s[j])):
				if a_s[j][k] == '1':
					s += '0'
				else:
					s += '1'
			a_s[j] = s
	ans = ''
	for j in range(len(a_s)):
		ans += a_s[j]
	ans += a[ind:n]
	if ans == b:
		return 'YES'
	else:
		return 'NO'
t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	print(fun(a, b, n))


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	(a, b) = (a + '0', b + '0')
	count = 0
	for i in range(n):
		val = a[i]
		if val == '1':
			count += 1
		else:
			count -= 1
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and count != 0:
			print('NO')
			break
	else:
		print('YES')


def solve():
	n = int(input())
	s1 = input()
	s2 = input()
	if s1 == s2:
		print('YES')
		return
	res = []
	(one, zero) = (0, 0)
	j = 0
	for i in range(n):
		if s1[i] == '0':
			zero += 1
		else:
			one += 1
		if zero == one:
			res.append([j, i])
			j = i + 1
	lst = list(s1)
	for i in res:
		st = i[0]
		end = i[1]
		if s1[st] == s2[st]:
			continue
		else:
			for j in range(st, end + 1):
				if s1[j] == '0':
					lst[j] = '1'
				else:
					lst[j] = '0'
	s1 = ''.join((i for i in lst))
	if s1 == s2:
		print('YES')
	else:
		print('NO')
t = int(input())
while t > 0:
	t -= 1
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	a = input() + '0'
	b = input() + '0'
	cnt = 0
	flag = True
	for i in range(n):
		if a[i] == '0':
			cnt += 1
		else:
			cnt -= 1
		if (a[i] != b[i] and a[i + 1] == b[i + 1] or (a[i] == b[i] and a[i + 1] != b[i + 1])) and cnt != 0:
			print('NO')
			flag = False
			break
	if flag:
		print('YES')


def solver(a, b):
	a = list(map(int, list(a)))
	b = list(map(int, list(b)))
	swapped_version = [1 if el == 0 else 0 for el in a]
	if a == b:
		return 'YES'
	if sum(a) != sum(b):
		return 'NO'
	answers = []
	valid_pref = []
	cur_sum = 0
	for i in range(0, len(a)):
		if a[i] == 1:
			cur_sum += 1
		elif a[i] == 0:
			cur_sum -= 1
		if cur_sum == 0:
			valid_pref.append(i)
	valid_pref = [len(a)] + valid_pref[::-1] + [0]
	swapped_bool = False
	for (x, y) in zip(valid_pref[1:], valid_pref[:-1]):
		if swapped_bool:
			compare = [1 if el == 0 else 0 for el in a[x:y]].copy()
		else:
			compare = a[x:y].copy()
		no_cond = compare != b[x:y]
		no_cond = no_cond and (not (compare[0] != b[x] and compare[1:y] == b[x + 1:y]))
		if no_cond:
			return 'NO'
		if compare != b[x:y]:
			swapped_bool = not swapped_bool
	return 'YES'
t = int(input())
answers = []
ls = []
a_s = []
b_s = []
for i in range(t):
	_ = input()
	a_s.append(input())
	b_s.append(input())
	ans = solver(a_s[-1], b_s[-1])
	answers.append(ans)
print('\n'.join(answers))


def Work():
	n = int(input())
	a = str(input())
	b = str(input())
	psbl = [0] * n
	o = 0
	z = 0
	for i in range(n):
		if a[i] == '0':
			z += 1
		else:
			o += 1
		if o == z:
			psbl[i] = 1
	i = n - 1
	f = 0
	while i > -1:
		if a[i] == b[i] and f == 0:
			i -= 1
		elif a[i] != b[i] and f == 1:
			i -= 1
		elif psbl[i]:
			f += 1
			f %= 2
			--i
		else:
			print('NO')
			return
	print('YES')
t = int(input())
for _ in range(t):
	Work()


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	pre = [[0, 0]]
	for i in range(n):
		if a[i] == '1':
			f = pre[-1].copy()
			f[1] = f[1] + 1
			pre.append(f)
		else:
			f = pre[-1].copy()
			f[0] = f[0] + 1
			pre.append(f)
	ans = 'YES'
	(i, j) = (n - 1, n - 1)
	turn = 0
	pre = pre[1:]
	while i >= 0:
		if turn % 2 == 0:
			if a[i] != b[i]:
				j = i
				while j >= 0 and a[j] != b[j]:
					j = j - 1
				j = j + 1
				if pre[i][0] == pre[i][1]:
					turn = turn + 1
					i = j - 1
				else:
					ans = 'NO'
					break
			else:
				i = i - 1
		elif a[i] == b[i]:
			j = i
			while j >= 0 and a[j] == b[j]:
				j = j - 1
			j = j + 1
			if pre[i][0] == pre[i][1]:
				turn = turn + 1
				i = j - 1
			else:
				ans = 'NO'
				break
		else:
			i = i - 1
	print(ans)


def sv():
	n = int(input())
	a = [1 if c == '1' else -1 for c in input()]
	b = [1 if c == '1' else -1 for c in input()]
	c1 = sum((1 for c in a if c == 1))
	m = 1
	for i in range(n - 1, -1, -1):
		if a[i] * m != b[i]:
			if c1 != i + 1 - c1:
				return False
			m *= -1
		if a[i] == 1:
			c1 -= 1
	return True
TC = int(input())
for tc in range(TC):
	print('YES' if sv() else 'NO')


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	zero = 0
	one = 0
	j = 0
	ans = []
	for i in range(n):
		if a[i] == '0':
			zero += 1
		if a[i] == '1':
			one += 1
		if zero == one:
			ans.append([j, i])
			j = i + 1
	for i in range(len(ans)):
		st = ans[i][0]
		end = ans[i][1]
		if a[st] == b[st]:
			continue
		else:
			for k in range(st, end + 1):
				if a[k] == '0':
					a[k] = '1'
				else:
					a[k] = '0'
	for i in range(n):
		if a[i] != b[i]:
			print('NO')
			break
	else:
		print('YES')


ram = int(input())
for ysbd in range(ram):
	w = int(input())
	u = input()
	v = input()
	a = 0
	b = 0
	c = 0
	d = 0
	for i in range(w):
		if abs(int(u[i])) != abs(c - int(v[i])):
			if a == b:
				if u[i] == '0':
					a = a + 1
				else:
					b = b + 1
				c = abs(c - 1)
			else:
				d = i
				break
		elif u[i] == '0':
			a = a + 1
		else:
			b = b + 1
	if d != 0:
		print('NO')
	elif a != b and c == 1:
		print('NO')
	else:
		print('YES')


T = int(input())
for t in range(T):
	n = int(input())
	a = input()
	b = input()
	idxs = [0 for i in range(n)]
	zeroct = [0 for i in range(n)]
	onect = [0 for i in range(n)]
	for i in range(n):
		if a[i] == '0':
			zeroct[i] = 1
		else:
			onect[i] = 1
		if a[i] != b[i]:
			idxs[i] = 1
	for i in range(1, n):
		zeroct[i] += zeroct[i - 1]
		onect[i] += onect[i - 1]
	swapped = 0
	ok = True
	for i in range(n - 1, -1, -1):
		if (swapped == 0 and idxs[i] == 1 or (swapped == 1 and idxs[i] == 0)) and zeroct[i] == onect[i]:
			swapped = 1 - swapped
		if swapped == 0:
			if idxs[i] == 0:
				continue
			else:
				ok = False
		if swapped == 1:
			if idxs[i] == 1:
				continue
			else:
				ok = False
	if ok:
		print('YES')
	else:
		print('NO')


import sys
import heapq
from collections import Counter
import bisect

def load_sys():
	return sys.stdin.readlines()

def load_local():
	with open('input.txt', 'r') as f:
		input = f.readlines()
	return input

def f(n, a, b):
	h = []
	(ones, zeros) = (0, 0)
	for (x, y) in zip(list(a), list(b)):
		if x == '0':
			zeros += 1
		else:
			ones += 1
		if h and (x == y) != h[-1]:
			return 'NO'
		if not h:
			h.append(x == y)
		if zeros == ones:
			h = []
	if h and h[0] == False:
		return 'NO'
	return 'YES'
input = load_sys()
for i in range(1, len(input), 3):
	n = int(input[i])
	a = input[i + 1]
	b = input[i + 2]
	print(f(n, a, b))


import sys
from sys import stdin

def is_good(a_part, b_part):
	if a_part == b_part:
		return True
	b_part_copy = ''
	for b in b_part:
		if b == '0':
			b_part_copy += '1'
		else:
			b_part_copy += '0'
	if a_part == b_part_copy:
		return True
	return False

def solve(N, A, B):
	a_start = -1
	a_status = 0
	b_status = 0
	for i in range(N):
		if A[i] == '0':
			a_status -= 1
		else:
			a_status += 1
		if B[i] == '0':
			b_status -= 1
		else:
			b_status += 1
		if a_status == 0:
			if b_status == 0:
				a_part = A[a_start + 1:i + 1]
				b_part = B[a_start + 1:i + 1]
				if not is_good(a_part, b_part):
					return 'NO'
				a_start = i
			else:
				return 'NO'
	if a_start == N - 1:
		return 'YES'
	else:
		a_part = A[a_start + 1:]
		b_part = B[a_start + 1:]
		if a_part == b_part:
			return 'YES'
		else:
			return 'NO'

def run():
	out = ''
	T = int(input())
	for i in range(T):
		N = int(input())
		A = input()
		B = input()
		print(solve(N, A, B))
run()


for i in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	zero = 0
	one = 0
	inv = False
	valid = True
	for i in range(0, n):
		if inv:
			if a[i] == b[i]:
				inv = False
				if zero != one:
					valid = False
					break
		elif a[i] != b[i]:
			inv = True
			if zero != one:
				valid = False
				break
		if a[i] == '0':
			zero += 1
		else:
			one += 1
	if valid:
		if inv and zero != one:
			print('NO')
		else:
			print('YES')
	else:
		print('NO')


def solve(n, a, b):
	if a == b:
		return 'YES'
	i = 0
	while i < n:
		c0 = 0
		c1 = 0
		j = i
		while j < n:
			if a[j] == '0':
				c0 += 1
			if a[j] == '1':
				c1 += 1
			if c0 == c1:
				break
			j += 1
		pa = a[i:j + 1]
		pb = b[i:j + 1]
		if c0 == c1:
			d = int(pa, 2) ^ int(pb, 2)
			m = int('1' * len(pa), 2)
			if d != 0 and d != m:
				return 'NO'
		elif pa != pb:
			return 'NO'
		i = j + 1
	return 'YES'
t = int(input())
while t > 0:
	n = int(input())
	a = input()
	b = input()
	print(solve(n, a, b))
	t -= 1


def solve():
	l = int(input())
	s1 = list(map(int, input()))
	s2 = list(map(int, input()))
	if s1 == s2:
		print('YES')
		return
	zeroes = ones = 0
	for i in range(l):
		if s1[i] == 0:
			zeroes += 1
		else:
			ones += 1
	xored = False
	for i in range(l - 1, -1, -1):
		if s1[i] ^ xored != s2[i]:
			if i % 2:
				if zeroes != ones:
					print('NO')
					return
				else:
					xored = not xored
			else:
				print('NO')
				return
		if s1[i] == 0:
			zeroes -= 1
		else:
			ones -= 1
	print('YES')
t = int(input())
for _ in range(t):
	solve()


x = int(input())
for i in range(x):
	n = int(input())
	s = input()
	m = input()
	d = 0
	b = []
	for j in range(n):
		if s[j] == '0':
			d = d + 1
		else:
			d = d - 1
		b.append(d)
	y = 0
	r = 0
	for k in range(n - 1, -1, -1):
		t = 0
		if y:
			if s[k] != m[k]:
				t = 1
			else:
				t = 0
		elif s[k] != m[k]:
			t = 0
		else:
			t = 1
		if t == 0 and b[k]:
			r = 1
			break
		if t == 0:
			if y == 0:
				y = 1
			else:
				y = 0
	if r:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	d = []
	zeroes = 0
	ones = 0
	for a_i in a:
		if a_i == '0':
			zeroes += 1
		else:
			ones += 1
		if zeroes == ones:
			d.append(1)
		else:
			d.append(0)
	possible = True
	flipped = False
	for i in range(n - 1, -1, -1):
		if flipped:
			if a[i] != b[i]:
				continue
			if d[i] != 1:
				possible = False
				break
			flipped = False
		else:
			if a[i] == b[i]:
				continue
			if d[i] != 1:
				possible = False
				break
			flipped = True
	if possible:
		print('YES')
	else:
		print('NO')


t = int(input())

def go(a, b):
	if a == b:
		return 'YES'
	else:
		zero = a.count('0')
		one = a.count('1')
		cnt = 0
		i = len(a) - 1
		while i >= 0:
			c = a[i]
			if cnt % 2 != 0:
				if c == '0':
					c = '1'
				else:
					c = '0'
			if c == b[i]:
				if c == '0':
					zero -= 1
				else:
					one -= 1
			elif one == zero:
				if c == '0':
					zero -= 1
				else:
					one -= 1
				cnt += 1
				(one, zero) = (zero, one)
			else:
				return 'NO'
			i -= 1
		return 'YES'
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	print(go(a, b))


for _ in range(int(input())):
	n = int(input())
	(a, b) = (input(), input())
	(x, y) = (0, 0)
	for i in range(n):
		if a[i] == '0':
			x += 1
		else:
			y += 1
	ans = 'YES'
	cnt = 0
	for i in range(n - 1, -1, -1):
		if a[i] != b[i] and cnt == 0 or (a[i] == b[i] and cnt == 1):
			if x != y:
				ans = 'NO'
				break
			(x, y) = (y, x)
			cnt = 1 - cnt
		if a[i] == '0':
			if cnt == 0:
				x -= 1
			else:
				y -= 1
		elif cnt == 0:
			y -= 1
		else:
			x -= 1
	print(ans)


def ii():
	return int(input())

def li():
	return [int(i) for i in input().split()]
for t in range(ii()):
	n = ii()
	a = input()
	b = input()
	ones = 0
	zeros = 0
	mat = a[0] == b[0]
	if a[0] == '0':
		zeros += 1
	else:
		ones += 1
	flag = 1
	N = n
	for i in range(N - 1, -1, -1):
		if a[i] != b[i]:
			n = i
			break
	if a == b:
		print('YES')
	else:
		for i in range(1, n + 1):
			if mat == 0 and a[i] == b[i]:
				mat = 1
				if zeros != ones:
					flag = 0
					break
			if mat == 1 and a[i] != b[i]:
				mat = 0
				if zeros != ones:
					flag = 0
					break
			if a[i] == '0':
				zeros += 1
			else:
				ones += 1
		if zeros != ones:
			flag = 0
		if flag == 0:
			print('NO')
		else:
			print('YES')


def recur(n, a, b):
	l = []
	x = 0
	y = 0
	for i in a:
		if i == '0':
			x += 1
		else:
			y += 1
		l.append([x, y])
	x = 0
	for i in range(n - 1, -1, -1):
		if a[i] != b[i] and x % 2 == 0 or (a[i] == b[i] and x % 2 == 1):
			if l[i][0] != l[i][1]:
				return False
			x += 1
	return True
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	if recur(n, a, b):
		print('YES')
	else:
		print('NO')


def func(a, b, l):
	a1 = a.count('1')
	a0 = l - a1
	switch = 0
	for i in range(l - 1, -1, -1):
		if switch == 1:
			if a[i] == '0':
				a[i] = '1'
			else:
				a[i] = '0'
		if a[i] != b[i]:
			if a1 != a0:
				return 'NO'
			else:
				if switch == 0:
					switch = 1
				else:
					switch = 0
				if a[i] == '0':
					a[i] = '1'
				else:
					a[i] = '0'
				(a1, a0) = (a0, a1)
		if a[i] == '0':
			a0 -= 1
		else:
			a1 -= 1
	return 'YES'
for h in range(int(input())):
	l = int(input())
	a = list(input())
	b = list(input())
	print(func(a, b, l))


try:
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = input()
		b = input()
		i = n - 1
		dp0 = [0] * n
		dp1 = [0] * n
		if a[0] == '0':
			dp0[0] = 1
		else:
			dp1[0] = 1
		for i in range(1, n, 1):
			if a[i] == '0':
				dp0[i] = dp0[i - 1] + 1
				dp1[i] = dp1[i - 1]
			elif a[i] == '1':
				dp1[i] = dp1[i - 1] + 1
				dp0[i] = dp0[i - 1]
		i = n - 1
		flag = True
		while i >= 0:
			while flag and i >= 0 and (a[i] == b[i]):
				i -= 1
			while not flag and i >= 0 and (a[i] != b[i]):
				i -= 1
			if flag and a[i] != b[i]:
				if dp0[i] == dp1[i]:
					while i >= 0 and a[i] != b[i]:
						i -= 1
					flag = False
				else:
					break
			if not flag and a[i] == b[i]:
				if dp0[i] == dp1[i]:
					while i >= 0 and a[i] == b[i]:
						i -= 1
					flag = True
				else:
					break
		if i == -1:
			print('YES')
		else:
			print('NO')
except EOFError:
	pass


import re

def invert(string):
	ans = ''
	for i in string:
		ans += '0' if i == '1' else '1'
	return ans

def main_code():
	length = int(input())
	string1 = input()
	string2 = input()
	one_count = 0
	zero_count = 0
	method = ''
	last_i = 0
	for i in range(length):
		if string1[i] == '0':
			zero_count += 1
		else:
			one_count += 1
		if zero_count == one_count and one_count != 0:
			if not (string1[last_i:i + 1] == string2[last_i:i + 1] or string1[last_i:i + 1] == invert(string2[last_i:i + 1])):
				print('NO')
				method = 'OVER'
				break
			last_i = i + 1
	if method == '':
		if not string1[last_i:] == string2[last_i:]:
			print('NO')
		else:
			print('YES')
for i in range(int(input())):
	main_code()


for _ in range(int(input())):
	n = int(input())
	a = input() + '0'
	b = input() + '0'
	c = 0
	ans = True
	for i in range(n):
		c = c + ((a[i] == '1') - (a[i] == '0'))
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and c != 0:
			print('NO')
			ans = False
			break
	if ans:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	ans = 'YES'
	(a1, a2) = (a.count('1'), a.count('0'))
	(b1, b2) = (b.count('1'), b.count('0'))
	if a1 != b1 or b2 != a2:
		print('NO')
	else:
		(r, o) = (0, 0)
		a1 = 0
		for i in range(n):
			if a[i] == b[i]:
				o += 1
			else:
				r += 1
			if a[i] == '0':
				a1 -= 1
			else:
				a1 += 1
			if a1 == 0:
				if r != 0 and o != 0:
					ans = 'NO'
					break
				else:
					(r, o) = (0, 0)
		if a1 != 0 and r != 0:
			ans = 'NO'
		print(ans)


from sys import maxsize, stdout, stdin, stderr
mod = int(1000000000.0 + 7)

def I():
	return int(stdin.readline())

def lint():
	return [int(x) for x in stdin.readline().split()]

def S():
	return input().strip()

def grid(r, c):
	return [lint() for i in range(r)]
from collections import defaultdict
import math
t = I()
for _ in range(t):
	n = I()
	a = input()
	b = input()
	f = 0
	flag = True
	o = 0
	e = 0
	p = []
	for i in range(n):
		if a[i] == '1':
			o += 1
		else:
			e += 1
		if o == e:
			p.append(True)
		else:
			p.append(False)
	for i in range(n):
		if f % 2 == 0:
			if a[n - 1 - i] != b[n - 1 - i]:
				if p[n - 1 - i] == True:
					f += 1
				else:
					flag = False
					break
		elif a[n - 1 - i] == '1':
			if b[n - 1 - i] == '1':
				if p[n - 1 - i] == True:
					f += 1
				else:
					flag = False
					break
		elif b[n - 1 - i] == '0':
			if p[n - 1 - i] == True:
				f += 1
			else:
				flag = False
				break
	if flag:
		print('YES')
	else:
		print('NO')


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	a += '0'
	b += '0'
	cnt = pr = x = 0
	for j in range(0, n):
		if a[j] == '1':
			x += 1
		else:
			x -= 1
		cnt = x
		if (a[j] == b[j]) != (a[j + 1] == b[j + 1]) and cnt != 0:
			pr = 1
			break
	if pr == 1:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input() + '0'
	b = input() + '0'
	c = 0
	for i in range(n):
		c += 1 if a[i] == '0' else -1
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and c != 0:
			print('NO')
			break
	else:
		print('YES')


import sys
from collections import *
from heapq import *
import math
import bisect

def input():
	return sys.stdin.readline()
for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	same = False
	diff = False
	ans = True
	zero = 0
	one = 0
	v = -1
	for i in a:
		v += 1
		if i == '0':
			zero += 1
		else:
			one += 1
		if i == b[v]:
			same = True
		else:
			diff = True
		if one == zero:
			if same and diff:
				ans = False
				break
			same = False
			diff = False
	if diff or not ans:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	flag = 0
	(zero, one) = (a.count('0'), a.count('1'))
	for i in range(n - 1, -1, -1):
		if int(a[i]) ^ flag != int(b[i]):
			if zero != one:
				print('NO')
				break
			flag = not flag
		zero -= a[i] == '0'
		one -= a[i] == '1'
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = list(input().strip())
	b = list(input().strip())
	ans = 0
	a1 = a.count('1')
	b1 = b.count('1')
	a0 = a.count('0')
	b0 = b.count('0')
	if a1 != b1:
		print('NO')
		continue
	for i in range(n - 1, -1, -1):
		if ans % 2 == 1:
			if a[i] == '1':
				a[i] = '0'
			else:
				a[i] = '1'
		if a[i] != b[i] and a1 == a0:
			ans += 1
			a[i] = b[i]
		if a[i] == '1':
			a1 -= 1
		else:
			a0 -= 1
	if a == b:
		print('YES')
	else:
		print('NO')


rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
YN = lambda x: print('YES') if x else print('NO')
mod = 10 ** 9 + 7
for _ in range(rn()):
	n = rn()
	a = rs()
	b = rs()
	diffs = []
	for i in range(n):
		if a[i] == b[i]:
			diffs.append(1)
		else:
			diffs.append(-1)
	poss = set()
	bal = 0
	for i in range(n):
		if a[i] == '0':
			bal += 1
		else:
			bal -= 1
		if bal == 0:
			poss.add(i)
	curr = 1
	ans = True
	for i in range(n - 1, -1, -1):
		if diffs[i] * curr == -1:
			curr *= -1
			ans = ans and i in poss
	YN(ans)


from collections import Counter
t = int(input())
for _ in range(t):
	n = int(input())
	s = input()
	si = input()
	co = Counter()
	for i in range(n):
		if s[i] == '1':
			co[i + 1] = co[i] + 1
		else:
			co[i + 1] = co[i] - 1
	f = 0
	a = 1
	for i in range(n - 1, -1, -1):
		if f == 0 and s[i] == si[i] or (f == 1 and s[i] != si[i]):
			continue
		elif co[i + 1] == 0:
			if f == 0:
				f = 1
			else:
				f = 0
		else:
			a = 0
			break
	if a == 1:
		print('YES')
	else:
		print('NO')


def solve_problem(x, y, n):
	if x == y:
		print('YES')
		return
	same = [True if x[i] == y[i] else False for i in range(n)]
	mustSwitch = set()
	for i in range(n - 1):
		if same[i] != same[i + 1]:
			mustSwitch.add(i + 1)
	if not same[-1]:
		mustSwitch.add(n)
	canSwitch = set()
	previousOnes = 0
	previousZeros = 0
	for i in range(n):
		if previousOnes == previousZeros and i % 2 == 0:
			canSwitch.add(i)
		if x[i] == '1':
			previousOnes += 1
		else:
			previousZeros += 1
	if previousOnes == previousZeros:
		canSwitch.add(n)
	if mustSwitch.issubset(canSwitch):
		print('YES')
	else:
		print('NO')

def solve():
	t = int(input())
	for i in range(0, t):
		n = int(input())
		x = input()
		y = input()
		solve_problem(x, y, n)
solve()


def solve():
	l = int(input())
	a = str(input())
	b = str(input())
	a1 = a + '0'
	b1 = b + '0'
	poss = 0
	for i in range(l):
		if a[i] == '1':
			poss = poss + 1
		else:
			poss = poss - 1
		if poss != 0:
			if a1[i] == b1[i] and a1[i + 1] != b1[i + 1] or (a1[i] != b1[i] and a1[i + 1] == b1[i + 1]):
				print('NO')
				return
	print('YES')

def main():
	t = int(input())
	while t > 0:
		t = t - 1
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	a = str(input())
	b = str(input())
	same = 0
	opp = 0
	c = True
	count = 0
	for i in range(n):
		if a[i] == b[i]:
			same += 1
		if a[i] != b[i]:
			opp += 1
		if a[i] == '1':
			count += 1
		if a[i] == '0':
			count -= 1
		if count == 0:
			if same != 0 and opp != 0:
				c = False
				break
			else:
				opp = 0
				same = 0
	if count != 0:
		if opp != 0:
			c = False
	if c == True:
		print('YES')
	else:
		print('NO')


for j in range(int(input())):
	a = int(input())
	b = input() + '0'
	c = input() + '0'
	d = 0
	for i in range(0, a):
		d += 1 if b[i] == '0' else -1
		if (b[i] == c[i] and b[i + 1] != c[i + 1] or (c[i] != b[i] and c[i + 1] == b[i + 1])) and d != 0:
			print('NO')
			break
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	revert = False
	(zeros_a, ones_a) = (a.count('0'), a.count('1'))
	for i in range(n - 1, -1, -1):
		if not (not revert and a[i] == b[i] or (revert and a[i] != b[i])):
			if zeros_a != ones_a:
				print('NO')
				break
			revert = not revert
		if a[i] == '0':
			zeros_a -= 1
		else:
			ones_a -= 1
	else:
		print('YES')


T = int(input())
for _ in range(T):
	n = int(input())
	a = input().split()[0]
	b = input().split()[0]
	a_counts = [0, 0]
	equal = True
	fine = True
	for i in range(n):
		if equal:
			if a[i] == b[i]:
				a_counts[int(a[i])] += 1
			else:
				if a_counts[0] != a_counts[1]:
					fine = False
					print('NO')
					break
				equal = False
				a_counts = [0, 0]
				a_counts[int(a[i])] += 1
		elif a[i] != b[i]:
			a_counts[int(a[i])] += 1
		else:
			if a_counts[0] != a_counts[1]:
				fine = False
				print('NO')
				break
			equal = True
			a_counts = [0, 0]
			a_counts[int(a[i])] += 1
	if fine:
		if not equal and a_counts[0] != a_counts[1]:
			print('NO')
		else:
			print('YES')


for nt in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	if a == b:
		print('YES')
		continue
	c0 = []
	if a[0] == '0':
		c0.append(1)
	else:
		c0.append(0)
	for i in range(1, n):
		if a[i] == '0':
			c0.append(c0[-1] + 1)
		else:
			c0.append(c0[-1])
	ans = 'YES'
	inv = 0
	for i in range(n - 1, -1, -1):
		if a[i] != b[i]:
			if not inv:
				if 2 * c0[i] != i + 1:
					ans = 'NO'
					break
				inv = 1
		elif inv:
			if 2 * c0[i] != i + 1:
				ans = 'NO'
				break
			inv = 0
	print(ans)


def bit_not(n):
	return bin((1 << len(n)) - 1 - int(n, 2))[2:].zfill(len(n))

def solve():
	n = int(input())
	a = input()
	b = input()
	if a == b:
		return True
	if a.count('0') != b.count('0'):
		return False
	l = 0
	az = a[:2].count('0')
	bz = b[:2].count('0')
	for i in range(2, n + 1):
		if not i & 1:
			if az == i // 2 and bz == i // 2:
				if not (a[l:i] == b[l:i] or bit_not(a[l:i]) == b[l:i]):
					return False
				l = i
		if i < n:
			if a[i] == '0':
				az += 1
			if b[i] == '0':
				bz += 1
	return a[l:] == b[l:]
for _ in range(int(input())):
	if solve():
		print('YES')
	else:
		print('NO')


def solve():
	n = int(input())
	for _ in range(n):
		l = int(input())
		(a, b) = (input(), input())
		ao = a.count('1')
		state = True
		for j in range(l - 1, -1, -1):
			if b[j] != a[j] and state or (a[j] == b[j] and (not state)):
				if ao != j - ao + 1:
					print('NO')
					break
				state = not state
			if a[j] == '1' and state or (a[j] == '0' and (not state)):
				ao -= 1
		else:
			print('YES')
solve()


def readArr():
	return [int(x) for x in input().split()]

def possible(a, b, m, n):
	same = True
	compl = True
	for i in range(m, n):
		if not a[i] == b[i]:
			same = False
			break
	for i in range(m, n):
		if a[i] == b[i]:
			compl = False
			break
	return same or compl

def solve():
	N = int(input())
	a = list(input())
	b = list(input())
	indices = [0]
	cnt_0 = 0
	cnt_1 = 0
	for i in range(N):
		if a[i] == '0':
			cnt_0 += 1
		elif a[i] == '1':
			cnt_1 += 1
		if cnt_1 == cnt_0:
			indices.append(i + 1)
	ans = 'YES'
	for i in range(1, len(indices)):
		if not possible(a, b, indices[i - 1], indices[i]):
			ans = 'NO'
			break
	if not a[indices[-1]:] == b[indices[-1]:]:
		ans = 'NO'
	print(ans)
T = int(input())
for t in range(T):
	solve()


def solve(n, a, b):
	a.append('0')
	b.append('0')
	count = 0
	for i in range(n):
		count += (a[i] == '1') - (a[i] == '0')
		if (a[i] == b[i]) != (a[i + 1] == b[i + 1]) and count != 0:
			return 'NO'
	return 'YES'
for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	print(solve(n, a, b))


cases = input()
cases = int(cases)
for c in range(0, cases):
	n = input()
	n = int(n)
	a = input()
	b = input()
	acopy = [ch for ch in a]
	ones_a = a.count('1')
	ones_b = b.count('1')
	if ones_a != ones_b:
		print('NO')
		continue
	currvaluea = a.count('0') - ones_a
	swic = False
	ok = True
	for z in range(0, n):
		z = n - z - 1
		curr = acopy[z]
		if b[z] != a[z] and (not swic) or (b[z] == a[z] and swic):
			if z % 2 == 0 or currvaluea != 0:
				print('NO')
				ok = False
				break
			swic = not swic
		if curr == '0':
			currvaluea = currvaluea - 1
		else:
			currvaluea = currvaluea + 1
	if ok:
		print('YES')


I = input
for _ in [0] * int(I()):
	I()
	a = b = 0
	f = 1
	for (x, y) in zip(I(), I()):
		a += 2 * int(x) - 1
		b += 2 * int(y) - 1
		f &= a in (b, -b)
	print('NYOE S'[f & (a == b)::2])


for _ in range(int(input())):
	n = int(input())
	s1 = input()
	s2 = input()
	reset = True
	balance = 0
	for i in range(n):
		if reset:
			diff = s1[i] == s2[i]
			reset = False
		elif (s1[i] == s2[i]) != diff:
			print('NO')
			break
		balance += 1 if s1[i] == '1' else -1
		if balance == 0:
			reset = True
	else:
		if reset or diff:
			print('YES')
		else:
			print('NO')


def bit(n, s1, s2):
	cnt = 0
	s1 += '0'
	s2 += '0'
	for i in range(n):
		cnt += 2 * (ord(s1[i]) - ord('0')) - 1
		if (s1[i] == s2[i]) != (s1[i + 1] == s2[i + 1]) and cnt != 0:
			return False
	return True
for i in range(0, int(input())):
	if bit(int(input()), input(), input()):
		print('YES')
	else:
		print('NO')


for _ in range(int(input())):
	n = int(input())
	s = str(input())
	s1 = str(input())
	(zero, one) = (0, 0)
	zcnt = [False] * n
	for (i, a) in enumerate(s):
		if a == '0':
			zero += 1
		else:
			one += 1
		if zero == one:
			zcnt[i] = True
	rev = 0
	i = n - 1
	while i >= 0:
		if s[i] == s1[i] and rev % 2 == 0 or (s[i] != s1[i] and rev % 2 == 1):
			i -= 1
		elif zcnt[i]:
			rev += 1
			i -= 1
		else:
			print('NO')
			break
	else:
		print('YES')


from sys import *
ws = lambda : map(int, stdin.readline().strip().split())
li = lambda : list(map(int, stdin.readline().strip().split()))
mod = 1000000007

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

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

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

def sortindex(l, a):
	c = []
	if a == -1:
		rev = True
	else:
		rev = False
	for i in range(len(l)):
		c.append([l[i], i])
	x = sorted(c, reverse=rev)
	print(x)
	c = []
	for i in range(len(l)):
		c.append(x[i][1])
	return c

def ispalindrome(s):
	c = s[::-1]
	if c == s:
		return True
	else:
		return False
for _ in range(int(input())):
	size = int(input())
	a = stdin.readline().strip()
	b = stdin.readline().strip()
	dic = {0: 1}
	t1 = 0
	t2 = 0
	for i in range(len(a)):
		if a[i] == '0':
			t1 += 1
		else:
			t2 += 1
		if t1 == t2:
			dic[i + 1] = 1
	i = 0
	flag = 0
	ini = 0
	while i < size:
		if a[i] == b[i]:
			if flag:
				if dic.get(ini, 0) == 1:
					flag = 0
					if dic.get(i, 0) == 1:
						flag = 0
					else:
						flag = -1
						break
				else:
					flag = -1
					break
		elif flag == 0:
			ini = i
			if dic.get(ini, 0) == 0:
				flag = -1
				break
			flag = 1
		if i == size - 1:
			if flag:
				if dic.get(ini, 0) == 1:
					flag = 0
					if dic.get(i + 1, 0) == 1:
						flag = 0
					else:
						flag = -1
						break
				else:
					flag = -1
					break
		i += 1
	if flag == -1:
		print('NO')
	else:
		print('YES')


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	c0 = a.count('0')
	c1 = a.count('1')
	a = a[::-1]
	b = b[::-1]
	switched = 0
	for (i, (x, y)) in enumerate(zip(a, b)):
		x = int(x)
		y = int(y)
		if (x + switched) % 2 == y:
			if x == 0:
				c0 -= 1
			else:
				c1 -= 1
			continue
		if c0 != c1:
			print('NO')
			break
		else:
			switched += 1
			if x == 0:
				c0 -= 1
			else:
				c1 -= 1
	else:
		print('YES')


import sys

def Main():
	t = int(sys.stdin.readline().strip())
	for _ in range(t):
		n = int(sys.stdin.readline().strip())
		a = list(sys.stdin.readline().strip())
		b = list(sys.stdin.readline().strip())
		one = a.count('1')
		zero = a.count('0')
		flag = False
		for i in range(n - 1, -1, -1):
			now = a[i]
			if flag:
				if now == '1':
					now = '0'
				else:
					now = '1'
			if now != b[i] and one == zero:
				flag = not flag
			elif now == b[i]:
				pass
			else:
				break
			if a[i] == '1':
				one -= 1
			else:
				zero -= 1
		else:
			print('YES')
			continue
		print('NO')
Main()


from io import BytesIO, IOBase
import sys
import math
import os
from collections import defaultdict
from math import ceil
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))

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

def mint():
	return map(int, input().split())

def mfloat():
	return map(float, input().split())

def solve():
	n = int(input())
	a = input()
	b = input()
	n = len(a)
	flips = [0] * n
	for i in range(n):
		flips[i] = a[i] != b[i]
	flippable = [0] * n
	zeros = ones = 0
	for i in range(n):
		zeros += a[i] == '0'
		ones += a[i] == '1'
		flippable[i] = ones == zeros
	flipped = False
	for i in range(n - 1, -1, -1):
		if flips[i]:
			if flipped:
				continue
			if flippable[i]:
				flipped = True
			else:
				print('NO')
				return
		else:
			if not flipped:
				continue
			if flippable[i]:
				flipped = False
			else:
				print('NO')
				return
	print('YES')

def main():
	t = int(input())
	for _ in range(t):
		solve()
main()


from os import path
import sys, time
mod = int(1000000000.0 + 7)
from math import ceil, floor, gcd, log, log2, factorial
from collections import defaultdict, Counter, OrderedDict, deque
from heapq import heapify, heappush, heappop
from bisect import *
from operator import mul
maxx = float('inf')
I = lambda : int(sys.stdin.buffer.readline())
tup = lambda : map(int, sys.stdin.buffer.readline().split())
lint = lambda : [int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda : sys.stdin.readline().strip('\n')
grid = lambda r: [lint() for i in range(r)]
stpr = lambda x: sys.stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
localsys = 0
start_time = time.time()
if path.exists('input.txt'):
	localsys = 1
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = input().strip()
	b = input().strip()
	if n % 2 and a[-1] != b[-1]:
		print('NO')
		continue
	if a == b:
		print('YES')
		continue
	(tot, l, z, o, cnt) = (0, [], 0, 0, 0)
	a = list(a)
	b = list(b)
	for i in range(n):
		if a[i] == '0':
			z += 1
		else:
			o += 1
		if a[i] != b[i]:
			cnt += 1
		if z == o:
			l.append([i, cnt])
			if cnt:
				tot += 1
				cnt = 0
	N = len(l)
	if N == 1:
		if l[0][1] == 0:
			pass
		else:
			for j in range(l[0][0] + 1):
				if a[j] == '1':
					a[j] = '0'
				else:
					a[j] = '1'
		print('YES') if a == b else print('NO')
		continue
	prev = 0
	for i in range(N):
		if tot > 0 and l[i][1]:
			for j in range(prev, l[i][0] + 1):
				if a[j] == '1':
					a[j] = '0'
				else:
					a[j] = '1'
			tot -= 1
		prev = l[i][0] + 1
	print('YES') if a == b else print('NO')
if localsys:
	print('\n\n\nTime Elased :', time.time() - start_time, 'seconds')


def solve():
	n = input()
	a = input()
	b = input()
	parts = []
	c0 = 0
	c1 = 0
	last_part = 0
	for j in range(len(a)):
		if a[j] == '1':
			c1 += 1
		else:
			c0 += 1
		if c0 == c1:
			parts.append((last_part, j))
			last_part = j + 1
	if len(parts) == 0:
		if a == b:
			return 'YES'
		else:
			return 'NO'
	for k in range(0, len(parts), 1):
		part = parts[k]
		start = part[0]
		end = part[1]
		t = 1
		if a[start] != b[start]:
			t = 0
		for j in range(start, end + 1, 1):
			tt = 1
			if a[j] != b[j]:
				tt = 0
			if tt != t:
				return 'NO'
	last_part = parts[len(parts) - 1]
	end = last_part[1] + 1
	if a[end:] != b[end:]:
		return 'NO'
	return 'YES'
t = int(input())
for i in range(t):
	print(solve())


def solve(a: str, b: str) -> bool:
	if a == b:
		return True
	flipped = list(map(lambda bit: '0' if bit == '1' else '1', a))
	flip_count = 0
	flippable = [False] * len(a)
	count_1 = 0
	for i in range(len(a)):
		if a[i] == '1':
			count_1 += 1
		if count_1 * 2 == i + 1:
			flippable[i] = True
	cur = a
	cur_index = len(a) - 1
	while True:
		while cur[cur_index] == b[cur_index]:
			cur_index -= 1
			if cur_index == -1:
				return True
		if flippable[cur_index]:
			if flip_count % 2 == 0:
				cur = flipped
			else:
				cur = a
			flip_count += 1
			cur_index -= 1
			if cur_index == -1:
				return True
		else:
			return False
	return True
t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	if solve(a, b):
		print('YES')
	else:
		print('NO')


x = int(input())
while x > 0:
	k = int(input())
	s = input()
	s1 = input()
	(a, b, c) = (0, 0, 1)
	for i in range(k):
		if s[i] == '1':
			a += 1
		else:
			b += 1
	f = 0
	for i in range(k - 1, -1, -1):
		if s[i] != s1[i]:
			if f == 0:
				if a != b:
					print('NO')
					c = 0
					break
				f = 1
		elif f == 1:
			if a != b:
				print('NO')
				c = 0
				break
			f = 0
		if f == 0:
			if s[i] == '1':
				a -= 1
			else:
				b -= 1
		elif s[i] == '1':
			b -= 1
		else:
			a -= 1
	if c == 1:
		print('YES')
	x -= 1


import sys
input = sys.stdin.readline

def ri():
	return [int(i) for i in input().split()]

def is_ok(a, b, st, en):
	same = 0
	oppo = 0
	for i in range(st, en):
		if a[i] == b[i]:
			same += 1
		else:
			oppo += 1
	return same == en - st or oppo == en - st

def main():
	t = ri()[0]
	for _ in range(t):
		n = ri()[0]
		a = input().split()[0]
		b = input().split()[0]
		prev = 0
		n0 = 0
		n1 = 0
		for i in range(n):
			if a[i] == '0':
				n0 += 1
			else:
				n1 += 1
			if n0 == n1:
				gg = is_ok(a, b, prev, i + 1)
				if not gg:
					print('NO')
					prev = -1
					break
				else:
					prev = i + 1
		if prev == -1:
			continue
		if prev != n and a[prev:] != b[prev:]:
			print('NO')
			continue
		print('YES')
main()


try:
	for _ in range(int(input())):
		n = int(input())
		a = input()
		b = input()
		a = a.replace(' ', '')
		b = b.replace(' ', '')
		a = list(a)
		b = list(b)
		count_one = a.count('1')
		count_zero = a.count('0')
		result = 0
		j = n - 1
		temp = 0
		while 1:
			if temp % 2 == 0:
				while j >= 0:
					if a[j] != b[j]:
						break
					if a[j] == '1':
						count_one -= 1
					else:
						count_zero -= 1
					j -= 1
				if j == -1:
					result = 1
					break
				elif count_zero != count_one:
					result = 0
					break
			else:
				while j >= 0:
					if a[j] == b[j]:
						break
					if a[j] == '0':
						count_one -= 1
					else:
						count_zero -= 1
					j -= 1
				if j == -1:
					result = 1
					break
				elif count_zero != count_one:
					result = 0
					break
			temp += 1
		if result == 0:
			print('NO')
		else:
			print('YES')
except EOFError:
	print(' ')


def solve(N, S, P):
	cs = [[0, 0] for _ in range(N)]
	for i in range(N):
		cs[i][0] = cs[i - 1][0]
		cs[i][1] = cs[i - 1][1]
		cs[i][int(S[i])] += 1
	flip_time = 0
	for i in range(N - 1, -1, -1):
		if S[i] != P[i] and (not flip_time & 1) or (S[i] == P[i] and flip_time & 1):
			if i + 1 & 1:
				return 'No'
			elif cs[i][0] != cs[i][1]:
				return 'No'
			flip_time += 1
	return 'Yes'
T = int(input())
for _ in range(T):
	N = int(input())
	(S, P) = (input(), input())
	ans = solve(N, S, P)
	print(ans)


def solve(s, r):
	zer = []
	one = []
	temp = 0
	(z, o) = (0, 0)
	l = len(s) - 1
	l1 = l
	for i in range(l + 1):
		if s[i] == '0':
			z += 1
			zer.append(z)
			one.append(o)
		else:
			o += 1
			zer.append(z)
			one.append(o)
	for i in range(l + 1):
		if s[l1] != r[l1] and temp == 0:
			if zer[l1] != one[l1]:
				return 'NO'
			else:
				temp = 1
		if s[l1] == r[l1] and temp == 1:
			if zer[l1] != one[l1]:
				return 'NO'
			else:
				temp = 0
		l1 -= 1
	return 'YES'
for i in range(int(input())):
	n = int(input())
	s = list(input())
	r = list(input())
	if s == r:
		print('YES')
	else:
		res = solve(s, r)
		print(res)


def isFlipOrSame(s1, s2):
	num_same = 0
	for i in range(len(s1)):
		if s1[i] == s2[i]:
			num_same += 1
	if num_same == 0 or num_same == len(s1):
		return True
	else:
		return False

def isSame(s1, s2):
	num_same = 0
	for i in range(len(s1)):
		if s1[i] == s2[i]:
			num_same += 1
	if num_same == len(s1):
		return True
	else:
		return False
t = int(input().strip())
for i in range(t):
	length = int(input().strip())
	s1 = input().strip()
	s2 = input().strip()
	if length <= 1:
		if s1 == s2:
			print('YES')
		else:
			print('NO')
		continue
	num0_1 = [0] * length
	num1_1 = [0] * length
	num0_2 = [0] * length
	num1_2 = [0] * length
	if s1[0] == '0':
		num0_1[0] = 1
	else:
		num1_1[0] = 1
	if s2[0] == '0':
		num0_2[0] = 1
	else:
		num1_2[0] = 1
	for j in range(1, length):
		if s1[j] == '0':
			num0_1[j] = num0_1[j - 1] + 1
			num1_1[j] = num1_1[j - 1]
		else:
			num0_1[j] = num0_1[j - 1]
			num1_1[j] = num1_1[j - 1] + 1
		if s2[j] == '0':
			num0_2[j] = num0_2[j - 1] + 1
			num1_2[j] = num1_2[j - 1]
		else:
			num0_2[j] = num0_2[j - 1]
			num1_2[j] = num1_2[j - 1] + 1
	pos = []
	pre_pos = -1
	for j in range(length):
		if num0_1[j] == num0_2[j] and num1_1[j] == num1_2[j] and (num0_1[j] == num1_1[j]):
			if pre_pos < j - 1:
				pos.append(j)
				pre_pos = j
	if len(pos) == 0:
		if isSame(s1, s2):
			print('YES')
		else:
			print('NO')
	elif len(pos) == 1:
		if not isFlipOrSame(s1[:pos[0] + 1], s2[:pos[0] + 1]):
			print('NO')
		elif not isSame(s1[pos[0] + 1:], s2[pos[0] + 1:]):
			print('NO')
		else:
			print('YES')
	else:
		if not isFlipOrSame(s1[:pos[0] + 1], s2[:pos[0] + 1]):
			print('NO')
			continue
		check = True
		for p in range(1, len(pos)):
			if not isFlipOrSame(s1[pos[p - 1] + 1:pos[p] + 1], s2[pos[p - 1] + 1:pos[p] + 1]):
				check = False
				break
		if not isSame(s1[pos[len(pos) - 1] + 1:], s2[pos[len(pos) - 1] + 1:]):
			check = False
		if check:
			print('YES')
		else:
			print('NO')


for y in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	p0 = a.count('0')
	p1 = n - p0
	q0 = b.count('0')
	q1 = n - q0
	if p0 == q0:
		foo = 0
		flag = 0
		for i in range(n - 1, -1, -1):
			if foo == 0:
				if a[i] == b[i]:
					pass
				elif p0 == p1:
					foo ^= 1
				else:
					flag = 1
				if a[i] == '1':
					p1 -= 1
				else:
					p0 -= 1
			else:
				if a[i] != b[i]:
					pass
				elif p0 == p1:
					foo ^= 1
				else:
					flag = 1
				if a[i] == '1':
					p1 -= 1
				else:
					p0 -= 1
		if flag == 0:
			print('YES')
		else:
			print('NO')
	else:
		print('NO')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	z = a.count('0')
	o = a.count('1')
	f = 0
	flag = 0
	for i in range(n - 1, -1, -1):
		if f == 0:
			if a[i] != b[i]:
				if z == o:
					f = 1
					temp = z
					z = o
					o = z
				else:
					flag = 1
					break
				if a[i] == '1':
					z -= 1
				else:
					o -= 1
			elif a[i] == '1':
				o -= 1
			else:
				z -= 1
		elif a[i] == b[i]:
			if z == o:
				f = 0
				temp = z
				z = o
				o = z
			else:
				flag = 1
				break
			if a[i] == '1':
				o -= 1
			else:
				z -= 1
		elif a[i] == '1':
			z -= 1
		else:
			o -= 1
	if flag == 1:
		print('NO')
	else:
		print('YES')


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	z = a.count('0')
	o = n - z
	ans = 1
	flag = 1
	i = n - 1
	while i >= 0:
		if flag == 1:
			if a[i] == b[i]:
				if a[i] == '1':
					o -= 1
				else:
					z -= 1
				i -= 1
				continue
			if z != o:
				ans = 0
				break
			flag = 0
			if a[i] == '1':
				o -= 1
			else:
				z -= 1
		else:
			if a[i] != b[i]:
				if a[i] == '1':
					o -= 1
				else:
					z -= 1
				i -= 1
				continue
			if z != o:
				ans = 0
				break
			flag = 1
			if a[i] == '1':
				o -= 1
			else:
				z -= 1
		i -= 1
	if ans == 1:
		print('YES')
	else:
		print('NO')


from sys import stdin
N = int(stdin.readline())
for t in range(N):
	n = int(stdin.readline())
	s1 = stdin.readline().strip()
	s2 = stdin.readline().strip()
	splitPoints = []
	c = 0
	for i in range(n):
		if i % 2 == 0 and c == i // 2:
			splitPoints.append(i)
		if s1[i] == '1':
			c += 1
	if n % 2 == 0 and c == n // 2:
		splitPoints.append(n)
	if len(splitPoints) == 1:
		if s1 != s2:
			print('NO')
		else:
			print('YES')
	else:
		lastPart = s1[splitPoints[-1]:]
		lastPart2 = s2[splitPoints[-1]:]
		bad = False
		if lastPart != lastPart2:
			print('NO')
		else:
			j = 0
			while j < len(splitPoints) - 1:
				act1 = s1[splitPoints[j]:splitPoints[j + 1]]
				act1_flip = ''.join(['0' if s == '1' else '1' for s in act1])
				act2 = s2[splitPoints[j]:splitPoints[j + 1]]
				if act1 != act2 and act1_flip != act2:
					print('NO')
					bad = True
					break
				j += 1
			if bad == False:
				print('YES')


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

def mapIn():
	return map(int, input().split())
for ii in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	flag = True
	c = 0
	d = {}
	for i in range(n):
		if a[i] == '1':
			c += 1
		if (i + 1) % 2 == 0 and c == (i + 1) // 2:
			d[i] = True
		else:
			d[i] = False
	alt = False
	for i in range(n - 1, -1, -1):
		if a[i] != b[i] and alt == True:
			continue
		elif a[i] != b[i] and alt == False and (d[i] == True):
			alt = True
		elif a[i] == b[i] and alt and (d[i] == True):
			alt = False
		elif a[i] == b[i] and alt == False:
			continue
		else:
			flag = False
			break
	if flag:
		print('YES')
	else:
		print('NO')


def inv(s):
	return s.translate({ord('1'): ord('0'), ord('0'): ord('1')})

def eq(s, t):
	return s == t or inv(s) == t
for _ in range(int(input())):
	n = int(input())
	s = input()
	t = input()
	ones = 0
	prefs = [0]
	for i in range(n):
		if s[i] == '1':
			ones += 1
		if ones * 2 == i + 1:
			prefs.append(i + 1)
	ok = True
	for i in range(len(prefs) - 1):
		ok = ok and eq(s[prefs[i]:prefs[i + 1]], t[prefs[i]:prefs[i + 1]])
	last = prefs[-1]
	ok = ok and s[last:] == t[last:]
	print('YES' if ok else 'NO')


def readInt():
	return int(input())

def readInts():
	return [int(x) for x in input().split()]

def readString():
	return input().rstrip()

def readCase():
	n = readInt()
	a = readString()
	b = readString()
	return (n, a, b)

def find_flip_points(s):
	allowed = []
	score = 0
	for bit in s:
		score += 1 if bit == '1' else -1
		allowed.append(score == 0)
	return allowed

def solve(n, a, b):
	flips = 0
	allowed = find_flip_points(a)
	for p in range(n - 1, -1, -1):
		if flips % 2 == 0:
			match = a[p] == b[p]
		else:
			match = a[p] != b[p]
		if not match:
			if not allowed[p]:
				return 'NO'
			else:
				flips += 1
	return 'YES'
cases = readInt()
for case in range(cases):
	print(solve(*readCase()))


t = int(input())

def solve(n, a, b):
	if n % 2 == 1:
		if a[-1] != b[-1]:
			return False
		n -= 1
	a = [c for c in a]
	c_a = [0] * n
	num1 = 0
	for i in range(n):
		if a[i] == 1:
			num1 += 1
		c_a[i] = num1
	b = [c for c in b]
	flip = False
	for i in range(n - 1, -1, -2):
		if flip:
			a[i] = a[i] ^ 1
			a[i - 1] = a[i - 1] ^ 1
		if a[i] == b[i] ^ 1 and a[i - 1] == b[i - 1] ^ 1 and (c_a[i] == i + 1 - c_a[i]):
			flip = not flip
		elif a[i] == b[i] and a[i - 1] == b[i - 1]:
			continue
		else:
			return False
	return True
for _ in range(t):
	n = int(input())
	a = [int(e) for e in input()]
	b = [int(e) for e in input()]
	if solve(n, a, b):
		print('YES')
	else:
		print('NO')


def inv(text):
	return [(el + 1) % 2 for el in text]

def is_pos(text1, text2):
	curr_ind = 0
	total = 0
	is_break = False
	for i in range(len(text1)):
		total += text1[i]
		if total == i + 1 - total:
			if text1[curr_ind:i + 1] == text2[curr_ind:i + 1] or inv(text1[curr_ind:i + 1]) == text2[curr_ind:i + 1]:
				curr_ind = i + 1
			else:
				print('NO')
				is_break = True
				break
	if not is_break:
		if text1[curr_ind:] == text2[curr_ind:]:
			print('YES')
		else:
			print('NO')
n = int(input())
for _ in range(n):
	input()
	text1 = [int(el) for el in input()]
	text2 = [int(el) for el in input()]
	is_pos(text1, text2)


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	if a == b:
		print('YES')
		continue
	ac = a.count('1')
	bc = b.count('1')
	flg = False
	for i in range(n - 1, -1, -1):
		if a[i] == b[i] and (not flg):
			if a[i] == '1':
				ac -= 1
			continue
		if a[i] != b[i] and flg:
			if a[i] == '1':
				ac -= 1
			continue
		if i % 2 == 0:
			print('NO')
			break
		if ac != (i + 1) // 2:
			print('NO')
			break
		flg = not flg
		if a[i] == '1':
			ac -= 1
	else:
		print('YES')


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	zeros = a.count('0')
	ones = a.count('1')
	swaps = 0
	f = True
	for j in range(0, n):
		i = n - j - 1
		if a[i] == b[i]:
			if swaps % 2 != 0:
				if zeros != ones:
					f = False
				else:
					swaps += 1
		elif swaps % 2 == 0:
			if zeros != ones:
				f = False
			else:
				swaps += 1
		if a[i] == '0':
			zeros -= 1
		else:
			ones -= 1
		if not f:
			break
	if f:
		print('YES')
	else:
		print('NO')


import sys, os, io
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = input().strip()
	b = input().strip()
	ind = [0] * len(a)
	zc = 0
	oc = 0
	for i in range(n):
		if a[i] == '0':
			zc += 1
		else:
			oc += 1
		if zc == oc:
			ind[i] = 1
	temp = 0
	flag = 0
	for i in range(n - 1, -1, -1):
		if temp == 0:
			if a[i] != b[i]:
				if ind[i]:
					temp = 1
				else:
					flag = 1
					break
		if temp == 1:
			if a[i] == b[i]:
				if ind[i]:
					temp = 0
				else:
					flag = 1
					break
	if flag:
		print('NO')
	else:
		print('YES')


import sys
import math
from collections import defaultdict, Counter, deque
import os
import sys
from io import BytesIO, IOBase
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')
t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	pre = [0] * n
	c = 0
	if a[0] == '0':
		c -= 1
	else:
		c += 1
	pre[0] = c
	if a[0] == b[0]:
		flag = 0
	else:
		flag = 1
	for j in range(1, n):
		if a[j] == '0':
			c -= 1
		else:
			c += 1
		pre[j] = c
		if a[j] == b[j]:
			if flag:
				if pre[j - 1] != 0:
					print('NO')
					break
				flag = 0
		elif flag == 0:
			if pre[j - 1] != 0:
				print('NO')
				break
			flag = 1
	else:
		if flag and pre[-1] != 0:
			print('NO')
		else:
			print('YES')


import sys
import math
from collections import defaultdict, Counter, deque
from heapq import heapify, heappop, heappush

def solve(test):
	n = int(input())
	a = input()
	b = input()
	count = 0
	eq_count = 0
	for i in range(n):
		if a[i] == b[i]:
			if count != 0:
				print('NO')
				return
			eq_count = eq_count + (1 if a[i] == '1' else -1)
		else:
			if eq_count != 0:
				print('NO')
				return
			count = count + (1 if a[i] == '1' else -1)
	print('YES') if count == 0 else print('NO')
test_cases = int(input())
for t in range(1, test_cases + 1):
	solve(t)


def rev(l, s, e):
	cl = ''
	for i in range(s, e + 1):
		if l[i] == '1':
			cl += '0'
		else:
			cl += '1'
	return cl
t = int(input())
for i in range(t):
	n = int(input())
	x1 = input()
	x2 = input()
	num0 = 0
	num1 = 0
	li = 0
	nl = False
	for j in range(n):
		if x1[j] == '1':
			num1 += 1
		else:
			num0 += 1
		if num0 == num1:
			if x1[li:j + 1] == x2[li:j + 1] or rev(x1, li, j) == x2[li:j + 1]:
				li = j + 1
			else:
				nl = True
				break
		if j == n - 1 and li != j + 1:
			if x1[li:j + 1] != x2[li:j + 1]:
				nl = True
	if nl:
		print('NO')
	else:
		print('YES')


import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
import functools
from operator import ixor
from decimal import Decimal
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	g = n
	for i in range(n - 1, -1, -1):
		if a[i] == b[i]:
			g -= 1
		else:
			break
	n = g
	a = a[:g]
	b = b[:g]
	e = [0] * n
	z = 0
	x = 0
	h = 0
	if g == 0:
		print('YES')
		continue
	l = abs(int(a[0]) - int(b[0]))
	for i in range(n):
		if a[i] == b[i] and l == 0:
			pass
		elif a[i] != b[i] and l == 1:
			pass
		elif z == x:
			e[i - 1] = 1
			l = 1 - l
		else:
			e[i - 1] = -1
			h = -1
			break
		if a[i] == '1':
			z += 1
		else:
			x += 1
	if h == -1 or z != x:
		print('NO')
	else:
		e = e[::-1]
		a = a[::-1]
		b = b[::-1]
		k = 0
		if n % 2 == 0:
			q = 0
		else:
			q = 1
		if q == 1 and a[0] == b[0] or q == 0:
			for i in range(q, n, 2):
				if a[i] == b[i] and a[i + 1] == b[i + 1] or (a[i] != b[i] and a[i + 1] != b[i + 1]):
					continue
				else:
					q = -1
					break
			if q == -1 or h == -1:
				print('NO')
			else:
				print('YES')
		else:
			print('NO')


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
tc = 1
tc = int(input())
for test in range(1, tc + 1):
	n = int(input())
	a = str(input())
	b = str(input())
	ans = []
	i = 0
	f = True
	(o, z) = (0, 0)
	f1 = False
	lol = []
	while i < n:
		cnt = 0
		while i < n and a[i] != b[i]:
			if a[i] == '0':
				o += 1
			else:
				z += 1
			i += 1
			cnt += 1
		if cnt > 0 and o != z:
			f = False
			break
		if f1 and lol[-1]:
			f = False
			break
		cnt = 0
		while i < n and a[i] == b[i]:
			if a[i] == '0':
				o += 1
			else:
				z += 1
			i += 1
			cnt += 1
			f1 = True
		lol.append(o != z)
	print('YES' if f else 'NO')


from collections import Counter

def all_diff(x, y):
	for i in range(len(x)):
		if x[i] == y[i]:
			return False
	return True

def solve(n, a, b):
	dj = -1
	for j in range(n, 0, -1):
		if a[j - 1] != b[j - 1]:
			dj = j
			break
	if dj == -1:
		return 'YES'
	a = a[:dj]
	b = b[:dj]
	if len(a) % 2 > 0:
		return 'NO'
	ca = Counter(a)
	cb = Counter(b)
	if ca['0'] != ca['1'] or cb['0'] != cb['1']:
		return 'NO'
	cnts = []
	(x, y) = (0, 0)
	for i in range(len(a)):
		if a[i] == '0':
			x += 1
		else:
			y += 1
		if x == y:
			cnts.append(i)
	for j in range(len(cnts), 0, -1):
		idx = cnts[j - 1]
		if j == 1:
			x = a[:idx + 1]
			y = b[:idx + 1]
		else:
			idx2 = cnts[j - 2]
			x = a[idx2 + 1:idx + 1]
			y = b[idx2 + 1:idx + 1]
		if x != y and (not all_diff(x, y)):
			return 'NO'
	return 'YES'
t = int(input())
for ti in range(t):
	n = int(input())
	a = input().strip()
	b = input().strip()
	res = solve(n, a, b)
	print(res)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = input()
	b = input()
	zero = []
	one = []
	(x, y) = (0, 0)
	for i in a:
		if i == '0':
			x += 1
		else:
			y += 1
		zero.append(x)
		one.append(y)
	k = n - 1
	tmp = False
	while k >= 0:
		if tmp == False:
			if a[k] != b[k]:
				if zero[k] != one[k]:
					break
				else:
					(zero, one) = (one, zero)
					tmp = True
		elif a[k] == b[k]:
			if zero[k] != one[k]:
				break
			else:
				(zero, one) = (one, zero)
				tmp = False
		k -= 1
	if k < 0:
		print('YES')
	else:
		print('NO')


for i in range(int(input())):
	n = int(input())
	s = input()
	r = input()
	a = [-1]
	t = 0
	for j in range(n):
		if s[j] == '1':
			t += 1
		else:
			t -= 1
		if t == 0:
			a.append(j)
	k = 'YES'
	for j in range(a[-1] + 1, n):
		if s[j] != r[j]:
			k = 'NO'
	for j in range(len(a) - 1, 0, -1):
		w = a[j]
		u = a[j - 1]
		z = 1
		p = 1
		for j in range(u + 1, w + 1):
			if s[j] == r[j]:
				z = 0
			if s[j] != r[j]:
				p = 0
		if z + p == 0:
			k = 'NO'
	print(k)


import math
cases = int(input())
for c in range(cases):
	moves = int(input())
	string1 = input()
	string2 = input()
	count = 0
	count0 = string1.count('0')
	count1 = string1.count('1')
	boolean = True
	inverse = False
	for i in range(len(string1) - 1, -1, -1):
		if not inverse and string1[i] != string2[i]:
			if count0 != count1:
				boolean = False
				break
			inverse = not inverse
			count += 1
		elif inverse and string1[i] == string2[i]:
			if count0 != count1:
				boolean = False
				break
			inverse = not inverse
			count += 1
		if string1[i] == '1':
			count1 -= 1
		else:
			count0 -= 1
	if boolean and count <= moves:
		print('YES')
	else:
		print('NO')


import os.path
from math import gcd, floor, ceil
from collections import *
from bisect import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

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

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

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

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

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	n = inp()
	a = st()
	b = st()
	a = list(map(int, a))
	b = list(map(int, b))
	pref = []
	cur = [0, 0]
	for i in a:
		cur[i] += 1
		pref.append(list(cur))
	add = 0
	for i in range(n - 1, -1, -1):
		if (a[i] + add) % 2 == b[i]:
			continue
		if pref[i][0] != pref[i][1]:
			pr('NO')
			return
		add += 1
	pr('YES')
for _ in range(inp()):
	solve()


def find(s, j):
	a = 0
	b = 0
	while j >= 0:
		if s[j] == '1':
			a += 1
		else:
			b += 1
		j -= 1
	return (a, b)
t = int(input())
for _ in range(t):
	n = int(input())
	org = input()
	conv = input()
	if org == conv:
		print('YES')
	else:
		j = n - 1
		flip = False
		(a, b) = find(org, j)
		flag = False
		if False:
			pass
		else:
			while j >= 0:
				if not flip:
					if conv[j] == org[j]:
						if org[j] == '1':
							a -= 1
						else:
							b -= 1
						j -= 1
						continue
					elif a != b:
						print('NO')
						flag = True
						break
					else:
						flip = True
						continue
				elif conv[j] != org[j]:
					if org[j] == '1':
						a -= 1
					else:
						b -= 1
					j -= 1
					continue
				elif a != b:
					print('NO')
					flag = True
					break
				else:
					flip = False
					continue
			if not flag:
				print('YES')


import math
t = int(input())
for j in range(t):
	n = int(input())
	a = input()
	b = input()
	count = 0
	i = n - 1
	c_0 = 0
	c_1 = 0
	arr_0 = []
	arr_1 = []
	flag = 0
	for k in range(n):
		if a[k] == '0':
			c_0 += 1
		else:
			c_1 += 1
		arr_0.append(c_0)
		arr_1.append(c_1)
	while i > 0:
		ch = a[i]
		if count % 2 != 0:
			if a[i] == '1':
				ch = '0'
			else:
				ch = '1'
		if ch != b[i] and arr_1[i] != arr_0[i]:
			flag = 1
			break
		if ch != b[i]:
			count += 1
		i -= 1
	if flag == 1:
		print('NO')
		continue
	ch = a[0]
	if count % 2 != 0:
		if a[0] == '1':
			ch = '0'
		else:
			ch = '1'
	if ch != b[0]:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	box = [0]
	nocount = 0
	yescount = 0
	res = True
	for i in a:
		if i == '0':
			nocount += 1
		else:
			yescount += 1
		if yescount == nocount:
			box.append(yescount * 2)
	if box[-1] != n:
		for x in range(box[-1], n):
			if a[x] != b[x]:
				res = False
				break
	box.reverse()
	for i in range(len(box) - 1):
		s = a[box[i + 1]]
		f = b[box[i + 1]]
		if s == f:
			for x in range(box[i + 1], box[i]):
				if a[x] != b[x]:
					res = False
					break
		if s != f:
			for x in range(box[i + 1], box[i]):
				if a[x] == b[x]:
					res = False
					break
	if n % 2 == 1:
		if a[-1] != b[-1]:
			res = False
	if res:
		print('YES')
	else:
		print('NO')


t = int(input())
for _ in range(t):
	n = int(input())
	a = input()
	b = input()
	o1 = a.count('1')
	o2 = b.count('1')
	z1 = n - o1
	z2 = n - o2
	k = False
	v = 0
	for i in range(n - 1, -1, -1):
		if b[i] != a[i] and k == False or (b[i] == a[i] and k == True):
			if o1 != z1:
				v = 1
				print('NO')
				break
			if a[i] == '1':
				o1 -= 1
			else:
				z1 -= 1
			k = not k
		elif a[i] == '1':
			o1 -= 1
		else:
			z1 -= 1
	if v == 0:
		print('YES')


t = int(input())
for i in range(t):
	n = int(input())
	a = input()
	b = input()
	q = 0
	w = 0
	zero = a.count('0')
	on = a.count('1')
	for j in range(n):
		if a[n - j - 1] != b[n - j - 1]:
			if q == 0 and zero != on:
				w = 1
			q += 1
		elif q > 0:
			if q % 2 != 0:
				w = 1
				break
			elif zero == on:
				q = 0
			else:
				w = 1
		if a[n - j - 1] == '0':
			zero -= 1
		else:
			on -= 1
	if w == 0:
		print('Yes')
	else:
		print('No')


def main(a, b, n):
	ps = []
	s = 0
	for i in range(n):
		if a[i] == '1':
			s += 1
		else:
			s -= 1
		ps.append(s)
	sign = True
	for i in range(n - 1, -1, -1):
		if sign and a[i] != b[i] or (not sign and a[i] == b[i]):
			if ps[i] != 0:
				return 'NO'
			else:
				sign = not sign
	return 'YES'
nn = int(input())
for _ in range(nn):
	n = int(input())
	a = input()
	b = input()
	print(main(a, b, n))


from collections import Counter
cases = int(input())
for t in range(cases):
	size = int(input())
	a = input()
	b = input()
	pos = size - 1
	flipped = False
	counts = Counter(a)
	failed = False
	while pos >= 0:
		if a[pos] != b[pos] and flipped == False or (a[pos] == b[pos] and flipped):
			if counts['1'] == counts['0']:
				flipped = not flipped
			else:
				failed = True
				break
		counts[a[pos]] -= 1
		pos -= 1
	if failed:
		print('NO')
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	z = 0
	o = 0
	if a[0] == b[0]:
		check = 0
	else:
		check = 1
	ans = 1
	for i in range(n):
		if a[i] == '0':
			z += 1
		else:
			o += 1
		if check == 0:
			if a[i] != b[i]:
				check = -1
		elif check == 1:
			if a[i] == b[i]:
				check = -1
		if o == z:
			if check == -1:
				ans = 0
				break
			else:
				ans = 1
			if i < n - 1 and a[i + 1] == b[i + 1] or i == n - 1:
				check = 0
			else:
				check = 1
	if check != 0:
		ans = 0
	if ans:
		print('YES')
	else:
		print('NO')


numtests = int(input())
for i in range(numtests):
	zeros = 0
	ones = 0
	lenstring = int(input())
	a = input()
	b = input()
	for j in range(lenstring):
		if a[j] == '0':
			zeros += 1
		else:
			ones += 1
	flip = False
	output = 'YES'
	for j in range(lenstring - 1, -1, -1):
		if not (not flip and a[j] == b[j] or (flip and a[j] != b[j])):
			if zeros != ones:
				output = 'NO'
				break
			else:
				flip = not flip
		if a[j] == '0':
			zeros -= 1
		else:
			ones -= 1
	print(output)


import math as m
i = int(input())
inp = []
for a in range(0, int(i)):
	input()
	inp += [[input(), input()]]

def equal_count(s):
	c0 = 0
	c1 = 0
	for c in s:
		if c == '0':
			c0 += 1
		else:
			c1 += 1
	return c0 == c1

def logic(a, b):
	n = len(a)
	S = a[0] == b[0]
	partitions = []
	isSame = []
	partition = [a[0]]
	for i in range(1, n):
		same = a[i] == b[i]
		if same == S:
			partition += [a[i]]
		else:
			partitions += [partition]
			isSame += [S]
			S = not S
			partition = [a[i]]
	partitions += [partition]
	isSame += [S]
	l = len(isSame)
	for i in range(l - 1, -2, -1):
		if i == -1:
			return 'YES'
		elif not isSame[i]:
			break
	for j in range(i + 1):
		if not equal_count(partitions[j]):
			return 'NO'
	return 'YES'
for i in inp:
	(a, b) = (i[0], i[1])
	print(logic(a, b))


t = int(input())
for c in range(t):
	n = int(input())
	a = list(input())
	b = list(input())
	cnt = 0
	val1 = [0] * (n + 1)
	val0 = [0] * (n + 1)
	val = [0] * (n + 1)
	flag = True
	for i in range(n):
		if i != 0:
			val0[i] = val0[i - 1]
			val1[i] = val1[i - 1]
		if a[i] == '0':
			val0[i] += 1
		if a[i] == '1':
			val1[i] += 1
		if val0[i] == val1[i]:
			val[i] = 1
	for i in range(n - 1, -1, -1):
		if cnt % 2 == 1:
			if a[i] == '0':
				a[i] = '1'
			else:
				a[i] = '0'
		if a[i] != b[i]:
			if val[i] == 0:
				flag = False
			cnt += 1
	if flag:
		print('YES')
	else:
		print('NO')


def flipTheBits(n, a, b):
	if a == b:
		return 'YES'
	changeArray = []
	z = 0
	o = 0
	for x in range(n):
		if a[x] == b[x]:
			if x == 0 or a[x - 1] == b[x - 1]:
				continue
			else:
				changeArray.append(x - 1)
		elif x == 0 or a[x - 1] != b[x - 1]:
			continue
		else:
			changeArray.append(x - 1)
	if a[-1] != b[-1]:
		changeArray.append(n - 1)
	i = 0
	for x in range(n):
		if a[x] == '0':
			z += 1
		else:
			o += 1
		if i < len(changeArray) and x == changeArray[i]:
			i += 1
			if z == o:
				continue
			else:
				return 'NO'
	return 'YES'
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(input())
	b = list(input())
	print(flipTheBits(n, a, b))


tcs = int(input())
for tc in range(tcs):
	n = int(input())
	a = list(map(int, list(input())))
	b = list(map(int, list(input())))
	f = 0
	a1 = a.count(1)
	a0 = a.count(0)
	for i in range(n - 1, -1, -1):
		if a[i] ^ f != b[i]:
			if a1 != a0:
				print('NO')
				break
			f = 1 - f
		a1 -= a[i] == 1
		a0 -= a[i] == 0
	else:
		print('YES')


for q in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	i = 0
	x = {'0': 0, '1': 0}
	possible = True
	while i < n:
		if a[i] != b[i]:
			if x['0'] != x['1']:
				possible = False
				break
			else:
				while i < n and a[i] != b[i]:
					x[a[i]] += 1
					i += 1
				if x['0'] != x['1']:
					possible = False
					break
		else:
			x[a[i]] += 1
			i += 1
	if possible:
		print('YES')
	else:
		print('NO')


def is_inv(a, b):
	one = False
	two = False
	for i in range(len(a)):
		if a[i] == b[i]:
			one = True
			if two:
				return False
		if a[i] != b[i]:
			two = True
			if one:
				return False
	return True
for _ in range(int(input())):
	n = int(input())
	a = str(input())
	b = str(input())
	count0 = 0
	count1 = 0
	zoz = [0]
	for i in range(n):
		if a[i] == '1':
			count1 += 1
		if a[i] == '0':
			count0 += 1
		if count1 == count0:
			zoz.append(i)
	for i in range(1, len(zoz)):
		if not is_inv(a[zoz[i - 1]:zoz[i] + 1], b[zoz[i - 1]:zoz[i] + 1]):
			print('NO')
			break
		else:
			zoz[i] += 1
	else:
		if a[zoz[-1]:] == b[zoz[-1]:]:
			print('YES')
		else:
			print('NO')


inn = lambda : int(input())
inm = lambda : map(int, input().split())
ins = lambda : str(input())
ina = lambda : list(map(int, input().split()))

def solve():
	n = inn()
	a = ins()
	b = ins()
	pref = [0] * n
	pref[0] = 1 if a[0] == '0' else -1
	for i in range(1, n):
		pref[i] = pref[i - 1] + (1 if a[i] == '0' else -1)
	flip = 0
	for i in range(n - 1, -1, -1):
		if flip:
			if a[i] != b[i]:
				continue
			elif pref[i] == 0:
				flip = 1 - flip
			else:
				print('NO')
				return
		elif a[i] == b[i]:
			continue
		elif pref[i] == 0:
			flip = 1 - flip
		else:
			print('NO')
			return
	print('YES')

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	flip = []
	cnt0 = 0
	cnt1 = 0
	for i in range(n):
		if a[i] == '0':
			cnt0 += 1
		else:
			cnt1 += 1
		if cnt0 == cnt1:
			flip.append(i)
	if flip:
		prev = 0
		ok = True
		same = True
		for i in range(len(flip)):
			curr = flip[i]
			same = False
			if a[prev] == b[prev]:
				same = True
			for j in range(prev, curr + 1):
				if same:
					if a[j] != b[j]:
						ok = False
				elif a[j] == b[j]:
					ok = False
			prev = curr + 1
		for i in range(prev, n):
			if a[i] != b[i]:
				ok = False
		if ok:
			print('YES')
		else:
			print('NO')
	elif a == b:
		print('YES')
	else:
		print('NO')


def solve(n, a, b):
	flip = False
	symm = [0] * (n + 1)
	for i in range(n):
		symm[i + 1] = symm[i] + (1 if a[i] == '1' else -1)
	for i in range(n - 1, -1, -1):
		x = a[i] if not flip else '0' if a[i] == '1' else '1'
		if x != b[i]:
			if symm[i + 1] != 0:
				return 'NO'
			else:
				flip ^= True
	return 'YES'
T = int(input())
for case in range(T):
	N = int(input())
	(A, B) = (input(), input())
	res = solve(N, A, B)
	print(f'{res}')


import sys
input = sys.stdin.readline
import math
import bisect
from copy import deepcopy as dc
from itertools import accumulate
from collections import Counter, defaultdict, deque

def ceil(U, V):
	return (U + V - 1) // V

def modf1(N, MOD):
	return (N - 1) % MOD + 1
inf = int(1e+20)
mod = int(1000000000.0 + 7)

def rle(lst):
	ans = []
	cnt = 1
	ini = lst[0]
	for i in range(1, len(lst)):
		if ini == lst[i]:
			cnt += 1
		else:
			ans.append((ini, cnt))
			cnt = 1
			ini = lst[i]
	ans.append((ini, cnt))
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	a = input()[:-1]
	b = input()[:-1]
	c = []
	for i in range(n):
		if a[i] == b[i]:
			c.append('0')
		else:
			c.append('1')
	r = rle(c)
	if r[-1][0] == '0':
		r.pop()
	f = True
	for (i, j) in r:
		if j % 2 != 0:
			f = False
			break
	if not f:
		print('NO')
		continue
	rc = [0]
	for (i, j) in r:
		rc.append(rc[-1] + j)
	rc = rc[1:]
	a0c = [0]
	a1c = [0]
	for i in range(n):
		if a[i] == '0':
			a0c.append(a0c[-1] + 1)
			a1c.append(a1c[-1])
		else:
			a1c.append(a1c[-1] + 1)
			a0c.append(a0c[-1])
	for i in rc:
		if a0c[i] != a1c[i]:
			f = False
			break
	if f:
		print('YES')
	else:
		print('NO')


import math
from collections import Counter
import bisect
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input()))
	b = list(map(int, input()))
	count = [0 for i in range(n)]
	if a[0]:
		count[0] = 1
	else:
		count[0] = -1
	for i in range(1, n):
		if a[i] == 0:
			count[i] = count[i - 1] - 1
		else:
			count[i] = count[i - 1] + 1
	c = 0
	flag = 0
	for i in range(n - 1, -1, -1):
		if c % 2:
			k = not a[i]
		else:
			k = a[i]
		if k != b[i]:
			if count[i] != 0:
				flag = 1
				break
			else:
				c += 1
	if flag:
		print('NO')
	else:
		print('YES')


import math
from collections import defaultdict
from sys import stdin
for _ in range(int(input())):
	n = int(input())
	a = input()
	b = input()
	flag = 0
	(zero, one) = (a.count('0'), a.count('1'))
	for i in range(n - 1, -1, -1):
		if int(a[i]) ^ flag != int(b[i]):
			if zero != one:
				print('NO')
				break
			flag = not flag
		zero -= a[i] == '0'
		one -= a[i] == '1'
	else:
		print('YES')


for _ in range(int(input())):
	n = int(input())
	a = list(input())
	b = list(input())
	iv = 0
	x = a.count('1')
	y = a.count('0')
	for i in range(n - 1, -1, -1):
		if (a[i] != b[i]) == (iv % 2 == 0):
			if x != y:
				print('NO')
				break
			else:
				iv += 1
		if (a[i] == '1') == (iv % 2 != 1):
			x -= 1
		else:
			y -= 1
	else:
		print('YES')