/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    private static IEnumerable<int> Leafs(TreeNode node) {
        if (node == null) {
            yield break;
        }

        var stack = new Stack<TreeNode>();
        stack.Push(node);

        while (stack.Count > 0) {
            var n = stack.Pop();

            if (n.left == null && n.right == null) {
                yield return n.val;
            }

            if (n.right != null) {
                stack.Push(n.right);
            }
            if (n.left != null) {
                stack.Push(n.left);
            }
        }
    }

    public bool LeafSimilar(TreeNode root1, TreeNode root2) {
        var xs = Leafs(root1).GetEnumerator();
        var ys = Leafs(root2).GetEnumerator();

        bool hasX = xs.MoveNext(), hasY = ys.MoveNext();
        for (; hasX && hasY; hasX = xs.MoveNext(), hasY = ys.MoveNext()) {
            if (xs.Current != ys.Current) {
                return false;
            }
        }

        return hasX == hasY;
    }
}