The number of nodes in each tree will be in the range [1, 200].
Both of the given trees will have values in the range [0, 200].
Solutions
Solution 1: DFS
We can use Depth-First Search (DFS) to traverse the leaf nodes of the two trees, storing the values of the leaf nodes in two lists $l_1$ and $l_2$ respectively. Finally, we compare whether the two lists are equal.
Time complexity is $O(n)$, and space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree.
1 2 3 4 5 6 7 8 9101112131415161718192021
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defleafSimilar(self,root1:Optional[TreeNode],root2:Optional[TreeNode])->bool:defdfs(root:Optional[TreeNode],nums:List[int])->None:ifroot.left==root.right:nums.append(root.val)returnifroot.left:dfs(root.left,nums)ifroot.right:dfs(root.right,nums)l1,l2=[],[]dfs(root1,l1)dfs(root2,l2)returnl1==l2
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcleafSimilar(root1*TreeNode,root2*TreeNode)bool{l1,l2:=[]int{},[]int{}vardfsfunc(*TreeNode,*[]int)dfs=func(root*TreeNode,nums*[]int){ifroot.Left==root.Right{*nums=append(*nums,root.Val)return}ifroot.Left!=nil{dfs(root.Left,nums)}ifroot.Right!=nil{dfs(root.Right,nums)}}dfs(root1,&l1)dfs(root2,&l2)returnreflect.DeepEqual(l1,l2)}