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.

思路:

  • 题意是求一颗二叉树的的最短路径
  • 思路能够參考求二叉树的深度的算法,还是用递归的思想,考虑上级节点和下级左右子树的关系

代码:

/**
 * 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));
        }
    }
}
posted @ 2018-03-19 18:02  zhchoutai  阅读(80)  评论(0编辑  收藏  举报