111. 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.

解题方法

Divide and conquer

public int minDepth(TreeNode root){
        if(root == null){
            return 0;
        }

        return DFS(root);
    }

    public int DFS(TreeNode root){
        //因為取Math.min, 所以access到null節點不可以盲目回傳0
        if(root == null){
            return Integer.MAX_VALUE;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        int left = DFS(root.left);
        int right = DFS(root.right);
        return Math.min(left, right) + 1;
    }

results matching ""

    No results matching ""