111. Minimum Depth of Binary Tree

来源:互联网 发布:淘宝网上批发市场 编辑:程序博客网 时间:2024/06/16 17:20

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.

Subscribe to see which companies asked this question.


Solution:

Tips:

post order visit


Java Code:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    // post order visit    public int minDepth(TreeNode root) {        if (null == root) {            return 0;        }        int leftDepth = minDepth(root.left);        int rightDepth = minDepth(root.right);                return leftDepth == 0 || rightDepth == 0 ? leftDepth + rightDepth + 1 : Math.min(leftDepth, rightDepth) + 1;    }}


0 0
原创粉丝点击