I. Title Description:

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.

For example, 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

Ii. Analysis of Ideas:

The depth of a binary tree

Depth of a binary tree: The depth of a node in the tree is the number of edges along its path to the root node. (The Algorithm by Robert Sedgewick and Kevin Wayne, 4th edition)

The height of a node in the tree is the number of simple paths from that node to the leaf node. The height of the tree is equal to the maximum depth of all nodes (the depth of the tree).

The depth of the tree

1. A tree has only one node or no node, and its depth is 0; 2. The root node of a binary tree has only the left subtree but no right subtree, so it can be judged that the depth of the binary tree should be the depth of the left subtree plus 1. 3. The root node of a binary tree has only the right subtree but no left subtree, so it can be judged that the depth of the binary tree should be the depth of the right tree plus 1. 4. The root node of a binary tree has both right and left subtrees, so it can be judged that the depth of the binary tree should be the greater value of the depth of the left and right subtrees plus 1.

Iii. AC Code:

var maxDepth = function(root) {
    // There are no nodes
    if(root===null) {return 0
    }
    // Only one root node
    if(root.left===null && root.right===null) {return 1
    }
    // recursive left subtree
    let leftMax = maxDepth(root.left)
    // Recursive right subtree
    let rightMax = maxDepth(root.right)
    // Returns the greater depth of the left and right subtrees plus 1
    return Math.max(leftMax,rightMax)+1
};
Copy the code

Iv. Summary:

1. The basic understanding of the depth of binary trees is discussed. What is tree depth, and the calculation rules and skills of tree depth.