Leetcode 872: Leaf-Similar Trees

grid47
grid47
Exploring patterns and algorithms
Aug 11, 2024 5 min read

Given two binary trees, determine if their leaf value sequences are identical. A binary tree’s leaf value sequence is the sequence of values of its leaves, from left to right, following the in-order traversal. Two trees are considered leaf-similar if the leaf values in both trees appear in the same order.
Problem
Approach
Steps
Complexity
Input: You are given two binary trees represented by their root nodes, `root1` and `root2`.
Example: Input: root1 = [1, 3, 4, null, null, 5, 6], root2 = [1, 2, 3, null, 4, 6, 5]
Constraints:
• The number of nodes in each tree is between 1 and 200.
• The values of the nodes are between 0 and 200.
Output: Return `true` if the two trees have identical leaf value sequences, otherwise return `false`.
Example: Output: true
Constraints:
• The output should be a boolean indicating whether the trees' leaf value sequences are identical.
Goal: The goal is to traverse both trees and compare their leaf sequences.
Steps:
• Perform a depth-first search (DFS) on both trees to collect the leaf values.
• Compare the leaf value sequences of both trees. If they are identical, return `true`; otherwise, return `false`.
Goal: The solution should be optimized to handle trees with a maximum of 200 nodes.
Steps:
• 1 <= number of nodes <= 200
• Each node's value is between 0 and 200.
Assumptions:
• The input trees are binary trees.
• The leaf nodes are the nodes without any children.
Input: Input: root1 = [1, 3, 4, null, null, 5, 6], root2 = [1, 2, 3, null, 4, 6, 5]
Explanation: Both trees have the same leaf value sequence [5, 6], so the output is `true`.

Input: Input: root1 = [1, 2, 3], root2 = [1, 3, 2]
Explanation: The leaf value sequences for root1 are [2, 3] and for root2 are [3, 2], which are not identical, so the output is `false`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus