diff --git a/cs/leaf-similar-trees.cs b/cs/leaf-similar-trees.cs new file mode 100644 index 0000000..0bef91b --- /dev/null +++ b/cs/leaf-similar-trees.cs @@ -0,0 +1,52 @@ +/** + * 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 Leafs(TreeNode node) { + if (node == null) { + yield break; + } + + var stack = new Stack(); + 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; + } +}