mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
cs: add “872. Leaf-Similar Trees”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
fe58c04720
commit
1ce3f94173
1 changed files with 52 additions and 0 deletions
52
cs/leaf-similar-trees.cs
Normal file
52
cs/leaf-similar-trees.cs
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue