본문 바로가기

프로그래밍 기술 노트/Problem Solving

[PS/C#] Leet Code - Algorithms - [Sum of Nodes with Even-Valued Grandparent] / [Minimum Depth of Binary Tree]

leetcode.com/problems/minimum-depth-of-binary-tree/

 

Minimum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/

 

Sum of Nodes with Even-Valued Grandparent - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

재귀적인 문제

 

위의 문제는

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