Topic:

Enter the root node of a binary tree to find the depth of the tree. The nodes (including root and leaf nodes) that pass from the root node to the leaf node form a path of the tree. The longest length of the path is the depth of the tree.

Such as:

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

    3
   / \
  9  20
    /  \
   15   7
Copy the code

Returns its maximum depth of 3.

Tip:

The number of nodes is less than = 10000

Ideas:

Recursively find the depth of the left and right subtrees, the greater of the two plus 1 is the depth of the binary tree. The depth of the binary tree is 0 when the root node is empty, and 1 when the left and right subtrees of the root node are empty.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        returnleftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); }}Copy the code

Title link:

Leetcode-cn.com/problems/er…