1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cs: add “872. Leaf-Similar Trees”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-09 12:39:06 +01:00
parent fe58c04720
commit 1ce3f94173
Signed by: mfocko
GPG key ID: 7C47D46246790496

52
cs/leaf-similar-trees.cs Normal file
View file

@ -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<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;
}
}