Leetcode 111: Minimum Depth of Binary Tree

问题描述

在这里插入图片描述

java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    //way1
    //递归  分治的思想
    public int minDepth(TreeNode root) {
        int depth=0;
        if(root==null)
            return depth;
        //分
        int depthLeft=0;
        int depthRight=0;
        //合
        if(root.left==null)
            return 1+minDepth(root.right);
        if(root.right==null)
            return 1+minDepth(root.left);
        depthLeft=minDepth(root.left);
        depthRight=minDepth(root.right);
        return Math.min(depthLeft,depthRight)+1;
    }
}
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103828037