872. Leaf-Similar Trees

cod3pineapple

codingpineapple

Posted on February 16, 2021

872. Leaf-Similar Trees

Description:

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

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

// DFS approach
// Staring from the left side of the tree, 
// push all leaf nodes from each root into 2 respective arrays
// Check if the values in those 2 arrays are the same
var leafSimilar = function(root1, root2) {
    const output1 = []
    const output2 = []

    dfs(root1, output1)
    dfs(root2, output2)

    return (output1.length == output2.length &&
            output1.every((val, index) => val === output2[index]));

    function dfs(node, output) {
        if(!node) return
        // Leaf node if the current ndoe has no children
        // Push value into it's respective array
        if(!node.left && !node.right) {
            output.push(node.val)
            return
        }
        if(node.left) dfs(node.left, output)
        if(node.right) dfs(node.right, output)
    }
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
cod3pineapple
codingpineapple

Posted on February 16, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

872. Leaf-Similar Trees
javascript 872. Leaf-Similar Trees

February 16, 2021

199. Binary Tree Right Side View
javascript 199. Binary Tree Right Side View

February 15, 2021