treebinary-tree

Recursive solution to compare the leaves of two binary trees returns wrong result


I am trying to solve LeetCode problem 872. Leaf Similar Trees:

Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.

enter image description here

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

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.

Example 1:

enter image description here

Output: true

Template code

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {boolean}
 */
var leafSimilar = function(root1, root2) {
    
};

My solution

var leafSimilar = function(root1, root2) {
    let leaf1 = [];
    let leaf2 = [];
    function dfs(root,leaf){
        if(!root){
            return;
        }
        if(root.left == null && root.right == null){
            leaf.push(root.val);
            return;
        } else {
            dfs(root.left, leaf);
            dfs(root.right,leaf);
        }
        
    }
    dfs(root1, leaf1);
    dfs(root2, leaf2);
    if(leaf1.length !== leaf2.length){return false;}
    leaf1.forEach((element, index) => {
        if(element == leaf2[index]){
            return true;
        }
    });
    return false;
};

It is returns false instead of the expected true for the above example #1. What am I doing wrong?


Solution

  • The problem is at your forEach loop. In the callback you return true, but that only exits the callback function, not leafSimilar. The only return statements you have in leafSimilar are of the form return false, so it can never return true.

    To fix this, use every instead of forEach.

    Not a bug, but you can just return the boolean expression element === leaf2[index] in that callback:

        return leaf1.every((element, index) => element == leaf2[index]);