Minimum Depth of Binary Tree----easy

来源:互联网 发布:js动态为div添加style 编辑:程序博客网 时间:2024/06/06 10:53

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.

Tags:Tree Depth-first Search



在二叉树深度查找稍作修改:
  • 对仅有左/右子树的情况取该子树递归计算深度

  • 对有左右子树或无子树情况直接递归计算深度

public class Solution {    public int minDepth(TreeNode root) {        if(root==null)return 0;        else if(root.left == null && root.right != null) return 1+minDepth(root.right);        else if(root.left != null && root.right == null) return 1+minDepth(root.left);        else{            int i = minDepth(root.left);            int j = minDepth(root.right);            return 1+(i>=j?j:i);        }    }}

0 0
原创粉丝点击