/**
* Definition for a binary tree node.
**/
class TreeNode
{
constructor(value, left, right)
{
this.value = value
this.left = left
this.right = right
}
}
/**
* @param {TreeNode} root1
* @param {TreeNode} root2
* @return {boolean}
*/
let leafSimilar = (root1, root2) => {
let root1BottomLeafs = getBottomLeaf(root1)
let isValid = validateBottomLeaf(root2, root1BottomLeafs)
// let root2BottomLeaf = getBottomLeaf(root2)
// if (root1BottomLeaf.length != root2BottomLeaf.length)
// return false
// for (let i = 0; i < root1.length; i++)
// if (root1BottomLeaf[i] != root2BottomLeaf[i])
// return false
return isValid
}
let getBottomLeaf = (root, list = []) =>
{
if (!root.left && !root.right)
{
list.push(root.value)
return list
}
if (root.left)
getBottomLeaf(root.left, list)
if (root.right)
getBottomLeaf(root.right, list)
return list
}
let validateBottomLeaf = (root, comparer, list = []) =>
{
if (!root.left && !root.right)
{
let position = list.length
if (comparer[position] !== root.value)
return false
list.push(root.value)
return true
}
if (root.left)
validateBottomLeaf(root.left, comparer, list)
if (root.right)
validateBottomLeaf(root.right, comparer, list)
if (comparer.length !== list.length)
return false
return true
}
Leave a Reply