1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/cs/leaf-similar-trees.cs
Matej Focko 1ce3f94173
cs: add “872. Leaf-Similar Trees”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-01-09 12:39:06 +01:00

52 lines
1.3 KiB
C#

/**
* 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;
}
}