cs: add «404. Sum of Left Leaves»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
1ab4b55fb1
commit
1711b319be
1 changed files with 34 additions and 0 deletions
34
cs/sum-of-left-leaves.cs
Normal file
34
cs/sum-of-left-leaves.cs
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
#if _MF_TEST
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
public class Solution {
|
||||||
|
private static bool IsLeaf(TreeNode node)
|
||||||
|
=> node != null && node.left == null && node.right == null;
|
||||||
|
|
||||||
|
private int Sum(TreeNode node, bool isLeft) {
|
||||||
|
if (node == null) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLeft && IsLeaf(node)) {
|
||||||
|
return node.val;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Sum(node.left, true) + Sum(node.right, false);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public int SumOfLeftLeaves(TreeNode root)
|
||||||
|
=> Sum(root, false);
|
||||||
|
}
|
Loading…
Reference in a new issue