Статья пока доступна только на английском.
Problem Description
You are given two binary trees.
All leaves of a tree form a leaf value sequence.
For example, for the tree above the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequences are the same.
Write a function that returns true if and only if the two given trees are leaf-similar.
Constraints
- The number of nodes in each tree is in the range
[1, 200] - The nodes of both trees have values in the range
[0, 200]
Examples
Input:
Answer: true
Solution
To solve the problem, we collect the leaf sequences of both trees and compare them.
For that we implement a separate function getSequence that builds the leaf value sequence of a given tree.
The function performs a classic depth-first search (DFS) and, when it meets a leaf (a node without children),
appends its value to the string sequence, separating values with semicolons.
We define sequence as an empty string beforehand and update it through a closure.
We could use arrays instead of strings, but then we would have to compare them element by element,
which would cost an extra k operations. Strings, on the other hand, can be compared directly with ==.
export type TreeNode = {
val: number;
left: TreeNode | null;
right: TreeNode | null;
};
export function leafSimilar(root1: TreeNode | null, root2: TreeNode | null): boolean {
if (!root1 || !root2) {
return false;
}
const first = getSequence(root1);
const second = getSequence(root2);
return first === second;
}
function getSequence(root: TreeNode): string {
let sequence = '';
const dfs = (node: TreeNode): void => {
if (!node.left && !node.right) {
sequence = `${sequence}${node.val};`;
}
if (node.left) {
dfs(node.left);
}
if (node.right) {
dfs(node.right);
}
};
dfs(root);
return sequence;
}Complexity Analysis
n1: the number of nodes in the first treen2: the number of nodes in the second treeh1: the height of the first treeh2: the height of the second tree
Time Complexity
O(n1 + n2), since we need to visit every node of both trees.
Space Complexity
Since we store the leaf sequences as strings, we treat that memory as constant. However, this is a recursive algorithm, so we need to account for the memory used by the call stack.
So the space complexity is O(h1 + h2).