https://leetcode.com/problems/minimum-depth-of-binary-tree/
이진 트리 주어졌을 때 최소 depth 반환
depth : root ~ 근처 leaf 노드 까지의 최소 길이
node traverse하면서 child depth 받고, 그 중 가장 작은 depth 반환
/**
* 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 {
public int MinDepth(TreeNode root) {
if (root == null) return 0;
return Traverse(root, 1);
}
public int Traverse(TreeNode node, int depth)
{
if (node.left != null && node.right != null)
{
return Math.Min(Traverse(node.left, depth + 1), Traverse(node.right, depth + 1));
}
else if (node.left != null) return Traverse(node.left, depth + 1);
else if (node.right != null) return Traverse(node.right, depth + 1);
else return depth;
}
}