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

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

1.解题思路

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

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.

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

1.解题思路

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

2.代码

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;
    }
}

tiffanytown
6 声望2 粉丝

keep learning