LeetCode(37)-Minimum Depth of Binary Tree


タイトル:
Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

考え方:
  • 題意は1粒の二叉木の最短経路
  • を求めることです
  • 構想は二叉木の深さを求めるアルゴリズムを参考にすることができるか,それとも再帰的な思想を用いて,上位ノードと下位左右のサブツリーの関係
  • を考慮することができる.
    コード:
    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
    public class Solution {
        public int minDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            if(root.left != null && root.right == null){
                return 1+minDepth(root.left);
            }else if(root.left == null && root.right != null){
                return 1+minDepth(root.right);
            }else{
                return 1+Math.min(minDepth(root.left),minDepth(root.right));
            }
        }
    }