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.

最大深度即从跟节点到最远距离叶子的距离,通过遍历可求

public int getMaxDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    return 1 + Math.max(getMaxDepth(root.left), getMaxDepth(root.right));
}

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.

注意: 判断最小深度的时候如果一边节点深度为0时需要返回另一边节点的深度

public int getMinDepth(TreeNode root) {
    if (root == null) {
        return 0;
    }
    int left = getMinDepth(root.left);
    int right = getMinDepth(root.right);
    if (left == 0 || right == 0) {
        return left > right ? left + 1: right + 1;
    }
    return 1 + Math.min(left, right);
}