var addBinary = function(a, b) {
let c = 0
let M = Math.max(a.length, b.length)
let i = 0
let result = ''
while (c || i < M) {
const ai = a[a.length - 1 - i]
? Number(a[a.length - 1 - i])
: 0
const bi = b[b.length - 1 - i]
? Number(b[b.length - 1 - i])
: 0
result = (ai + bi + c) % 2 + result
c = Math.floor((ai + bi + c) / 2)
i++
}
return result
}
var findMinHeightTrees = function (n, edges) {
if (n === 1) return [0]
if (n === 2) return edges[0]
const map = []
for (var i = 0; i < n - 1; i++) {
if (typeof map[edges[i][0]] === 'undefined') map[edges[i][0]] = []
if (typeof map[edges[i][1]] === 'undefined') map[edges[i][1]] = []
map[[edges[i][0]]].push(edges[i][1])
map[[edges[i][1]]].push(edges[i][0])
}
let end = []
for (var i = 0; i < map.length; i++){
if(map[i].length === 1) end.push(i)
}
while (n > 2) {
const newEnds = []
for (var i = 0; i < end.length; i++){
const mapLast = map[end[i]].pop()
map[mapLast].splice(map[mapLast].indexOf(end[i]), 1)
if (map[mapLast].length === 1) {
newEnds.push(mapLast)
}
}
n -= end.length
end = newEnds
}
return end
}