leetcode104_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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

与相等二叉树和对称二叉树的题目一致,用的递归的方法,且先处理无左右节点的根节点为空的情况。

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null){return 0;}//如果空二叉树(根节点为空)则返回0;
        else{
            return (1 + Math.max(maxDepth(root.left),maxDepth(root.right)));//如果根节点不为空,则返回1+左右树的最大深度。
        }       
    }
}

猜你喜欢

转载自blog.csdn.net/lilililililydia/article/details/85162686