Similar Problems
Similar Problems not available
Leaf Similar Trees - Leetcode Solution
LeetCode: Leaf Similar Trees Leetcode Solution
Difficulty: Easy
Topics: tree binary-tree depth-first-search
The Leaf Similar Trees problem on Leetcode is a problem that involves comparing the leaf values of two binary trees. The objective of the problem is to determine whether the leaf values of the two trees are the same. If the leaf values of the trees are the same, the function should return true. If not, it should return false.
Here is a detailed solution to the problem:
-
Define a function
leafSimilar
that takes two binary trees as its arguments. -
Define an inner function
getLeaves
that takes a binary tree as its argument and returns an array of its leaf values.function getLeaves(root) { let leaves = []; function traverse(node) { if (node == null) { return; } if (node.left == null && node.right == null) { leaves.push(node.val); return; } traverse(node.left); traverse(node.right); } traverse(root); return leaves; }
-
Call the
getLeaves
function on both trees.let leaves1 = getLeaves(root1); let leaves2 = getLeaves(root2);
-
Compare the two arrays of leaves and return true if they are the same, false otherwise.
return JSON.stringify(leaves1) === JSON.stringify(leaves2);
The solution uses a recursive approach. The getLeaves
function recursively traverses the binary tree and adds the leaf values to an array. The arrays of leaf values for both trees are then compared using JSON.stringify
to check if they are equal. If the arrays are equal, the function returns true. Otherwise, it returns false.
Leaf Similar Trees Solution Code
1