Google | Onsite | 🌳 Leaf-Similar Trees
2102

Given 2 binary trees root1 and root2. Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence. For example

	  "x"
	 /   \
 "abc"   "m"
        /   \
     "de"   "y"
            /
          "f"

in the given tree above, the leaf value sequence is (a, b, c, d, e, f).

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 are leaf-similar.

Example 1:

Input:
	root1
	 "xyz"
	 /   \
 "abcd"  "aabc"

	root2
	  "xy"
	 /   \
 "abc"  "daabc"

Output: true
Explanation: (a, b, c, d, a, a, b, c) = (a, b, c, d, a, a, b, c)

Example 2:

Input:
	root1
	 "xyz"
	 /   \
 "abcd"  "aabc"

	root2
	  "xy"
	 /   \
 "abc"  "aabc"

Output: false
Explanation: (a, b, c, d, a, a, b, c) != (a, b, c, a, a, b, c)

Expected O(1) space solution (recursion stack does count as additional space). Tree node structure is up to you:

class TreeNode {
	String val;
	TreeNode left;
	TreeNode right;
	// add whatever fields you need
}
My solution

Java: https://leetcode.com/playground/VSrQ7Zcm

Comments (8)