leetcode.com/problems/minimum-depth-of-binary-tree/
leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
재귀적인 문제
위의 문제는
public class Solution
{
public int MinDepth(TreeNode root)
{
return recursiveInorder(root);
}
public int recursiveInorder(TreeNode root)
{
if (root == null)
{
return 0;
}
else if (root.left == null && root.right == null)
{
return 1;
}
else if (root.left == null && root.right != null)
{
return recursiveInorder(root.right) + 1;
}
else if (root.right == null && root.left != null)
{
return recursiveInorder(root.left) + 1;
}
var left = recursiveInorder(root.left) + 1;
var rigth = recursiveInorder(root.right) + 1;
return left < rigth ? left : rigth;
}
}
요롷게
아래 문제는
public class Solution
{
public int GrandChildSum(TreeNode root)
{
var childrenCandidate = new int?[] {
root?.left?.left?.val,
root?.left?.right?.val,
root?.right?.left?.val,
root?.right?.right?.val };
var children = childrenCandidate.Where(x => x.HasValue).Select(x => x.Value);
return children.Sum();
}
public bool isEven(TreeNode a) => isEven(a.val);
public bool isEven(int a) => a % 2 == 0;
public int SumEvenGrandparent(TreeNode root)
{
return recursiveInorder(root);
}
public int recursiveInorder(TreeNode root)
{
if (root == null)
{
return 0;
}
if (isEven(root))
{
return GrandChildSum(root) + recursiveInorder(root.left) + recursiveInorder(root.right);
}
else
{
return recursiveInorder(root.left) + recursiveInorder(root.right);
}
}
}
요롷게 풀었다.
아래가 미디움이고 위가 이지인데
개인적으로는 미디움이 더 쉬웠던듯
728x90
'프로그래밍 기술 노트 > Problem Solving' 카테고리의 다른 글
[PS/C#] HackerRand - Algorithms - The Maximum Subarray (0) | 2020.11.03 |
---|---|
[PS/Clojure] HackerRand - Algorithms - Queen's Attack (0) | 2020.06.10 |
[PS/Clojure] HackerRand - Algorithms - Absolute Permutation (0) | 2020.06.08 |
[PS/Clojure] HackerRand - Algorithms - Forming a Magic Square (0) | 2020.06.05 |
[PS/Clojure] HackerRand - Algorithms - Sherlock and Cost (0) | 2020.06.05 |