July 7th 2023

Leaf-Similar Trees — Typescript

Problem Description permalink

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Solution permalink

/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/


function findLeaves(root: TreeNode | null): number[] {
if (root == null){
return []
}

if (root.left == null && root.right == null){
return [root.val]
}

return [...findLeaves(root.left), ...findLeaves(root.right)]
}

function arrayEqual<T>(left: T[], right: T[]): boolean {
if (left.length !== right.length){
return false;
}

for (var i=0; i<left.length; i++){
if (left[i] !== right[i]){
return false
}
}

return true
}


function leafSimilar(root1: TreeNode | null, root2: TreeNode | null): boolean {
return arrayEqual(findLeaves(root1), findLeaves(root2))
};

Discussion permalink

I like that this is testable. This is not clever code but it is simple and readable and unless I was presented with more information about why this needed to be faster or more memory efficient I would be inclined to ship this.