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.

 

Hide Tags
  Tree Depth-first Search  

链接: http://leetcode.com/problems/minimum-depth-of-binary-tree/

题解:

求二叉树最短路径长度。依然使用DFS递归求解。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {

    public int minDepth(TreeNode root) {

        if(root == null)

            return 0;

        if(root.left != null && root.right != null)

            return 1 + Math.min(minDepth(root.left), minDepth(root.right));

        else if(root.left == null)

            return 1 + minDepth(root.right);

        else

            return 1 + minDepth(root.left);

    }

}

 

测试:

你可能感兴趣的:(binary)