头图

Topic : Given a binary tree, find its maximum depth. The depth of a binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.

Description : A leaf node is a node that has no children.

link : Leetcode - Primary Algorithm - Tree - Maximum Depth of Binary Tree .

Example :

Given a binary tree [3, 9, 20, null, null, 15, 7]
  
    3
   /  \
  9   20
     /  \
    15   7
  
Returns its maximum depth of 3.

Tags : tree, depth-first search, breadth-first search, binary tree

idea : Find the subtree with the largest depth in the tree, treat it as a new tree, and continue to find the deeper one from the new tree. Recursively until the critical point, that is, when the root of the tree is empty, it means that the tree does not exist, the depth is 0, the recursion ends, and the depth is +1 for each recursion in it.

main Go code is as follows:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    i := 0
    j := 0
    if root == nil {
        return 0
    }
    i = maxDepth(root.Left) + 1
    j = maxDepth(root.Right) + 1
    if i < j {
        i, j = j, i
    }
    return i
}

submits screenshot :
在这里插入图片描述
official answer : The official uses recursive DFS (Depth-First-Search), the maximum depth of the tree = the height of the root node (root is 1) + the greater of the maximum depth of the left and right subtrees. And how to find the maximum depth of the left and right subtrees? Take the left subtree as an example, consider it as a new tree, then its maximum depth is: the height of the root node (the root is 1) + the greater of the maximum depth of the left and right subtrees. This is where the recursion is found. When the critical point is reached, that is, when the root of the tree is empty, it means that the tree does not exist, the depth is 0, and the recursion ends.

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root == nil{
        return 0
    }
    return max(maxDepth(root.Left), maxDepth(root.Right)) + 1
}

func max(a,b int)int {
    if a > b {
        return a
    }
    return b
}

土豆
17 声望5 粉丝