[Leetcode-Tree]Maximum / Minimum Depth of Binary Tree

Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.node

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.rest

1.解题思路 code

用递归实现很简单,对于每一个根节点,最大深度就等于左子树的最大深度和右子树的最大深度的较大值。htm

public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)  return 0;
        int leftmax=maxDepth(root.left);
        int rightmax=maxDepth(root.right);
        return Math.max(leftmax,rightmax)+1;
    }
}

Minimum Depth of Binary Tree递归

Given a binary tree, find its minimum depth.it

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.io

1.解题思路class

本题的注意点在于若是某个根节点有一边的子树为空,那么它的深度就等于另外一边不为空的子树的深度,其余的逻辑与上一题相同。test

2.代码im

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null&&root.right!=null) 
            return minDepth(root.right)+1;
        if(root.right==null&&root.left!=null)
            return minDepth(root.left)+1;
        int leftmin=minDepth(root.left);
        int rightmin=minDepth(root.right);
        return Math.min(leftmin,rightmin)+1;
    }
}
相关文章
相关标签/搜索