Consider all the leaves of a binary tree from left to right order form a leaf value sequence. For example, in the given tree:
3
/ \
5 1
/ \ / \
6 2 9 8
/ \
7 4
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, even if the structure of the trees is different.
Write a function to determine if two given binary trees are leaf-similar. The trees will be provided in the form of their root nodes.
True
if the leaf sequences are the same, and False
otherwise.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def leafSimilar(root1: TreeNode, root2: TreeNode) -> bool:
def get_leaf_sequence(root):
if not root:
return []
leaves = []
def dfs(node):
if not node:
return
if not node.left and not node.right:
leaves.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return leaves
return get_leaf_sequence(root1) == get_leaf_sequence(root2)
# Example usage:
# tree1 = TreeNode(3)
# tree1.left = TreeNode(5)
# tree1.right = TreeNode(1)
# tree1.left.left = TreeNode(6)
# tree1.left.right = TreeNode(2)
# tree1.left.right.left = TreeNode(7)
# tree1.left.right.right = TreeNode(4)
# tree1.right.left = TreeNode(9)
# tree1.right.right = TreeNode(8)
# tree2 = TreeNode(3)
# tree2.left = TreeNode(5)
# tree2.right = TreeNode(1)
# tree2.left.left = TreeNode(6)
# tree2.left.right = TreeNode(2)
# tree2.left.right.left = TreeNode(7)
# tree2.left.right.right = TreeNode(4)
# tree2.right.left = TreeNode(9)
# tree2.right.right = TreeNode(8)
# print(leafSimilar(tree1, tree2)) # Output: True
get_leaf_sequence
that extracts the leaf nodes of a tree in left-to-right order.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?