0872. Leaf Similar Trees

872. Leaf-Similar Trees #

Problem #

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

https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png

For example, in the given tree above, 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.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

  • Both of the given trees will have between 1 and 100 nodes.

Problem Summary #

Consider all the leaves of a binary tree. The values of these leaves arranged from left to right form a leaf value sequence. For example, as shown in the figure above, the given tree has a leaf value sequence of (6, 7, 4, 9, 8). If the leaf value sequences of two binary trees are the same, then we consider them leaf-similar. If the two given trees with head nodes root1 and root2 are leaf-similar, return true; otherwise return false.

Note:

  • The two given trees may have 1 to 200 nodes.
  • The values on the two given trees are between 0 and 200.

Solution Approach #

  • Given 2 trees, if the arrays formed by the leaf nodes of the 2 trees are exactly the same, then the 2 trees are considered “leaf-similar”. Given any 2 trees, determine whether the 2 trees are “leaf-similar”.
  • Easy problem. Perform DFS traversal on the 2 trees separately, collect all the leaf nodes, and then compare whether the arrays formed by the leaf nodes are exactly the same.

Code #

func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
	leaf1, leaf2 := []int{}, []int{}
	dfsLeaf(root1, &leaf1)
	dfsLeaf(root2, &leaf2)
	if len(leaf1) != len(leaf2) {
		return false
	}
	for i := range leaf1 {
		if leaf1[i] != leaf2[i] {
			return false
		}
	}
	return true
}

func dfsLeaf(root *TreeNode, leaf *[]int) {
	if root != nil {
		if root.Left == nil && root.Right == nil {
			*leaf = append(*leaf, root.Val)
		}
		dfsLeaf(root.Left, leaf)
		dfsLeaf(root.Right, leaf)
	}
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文