“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

[B] [C] [D]

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.

The problem is very simple, we just need to recursively get the height of the subtree, the height of the current node in the process of backtracking, and finally when backtracking to the root node, we get the depth of the whole tree. The code is as follows:

var maxDepth = function(root) {
    function getHeight(root){
        if(root === null) return 0;
        return Math.max(getHeight(root.left),getHeight(root.right))+1
    }
    return getHeight(root);
};
Copy the code

At this point we are done with leetcode- finger Offer 55 i-binary tree depth

If you have any questions or suggestions, please leave a comment!