【LeetCode】104. Maximum depth of binary tree

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.

Note:  A leaf node refers to a node without child nodes.

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

    3
   / \
  9  20
    /  \
   15   7

Return its maximum depth of 3 .

answer

source code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }
}

Summarize

At first, I wanted to use depth-first search to update the current maximum depth every time I reached a child node, but after writing it, I found that there were too many parameters and the idea was messy (to pass in the current maximum value, the current layer number must also be recursive every time) keep changing). After that, I rearranged my thinking and thought carefully about what to consider as a sub-problem, that is, the maximum depth of the binary tree corresponding to the current node. When recursing, I can compare the depth of the left and right sub-binary trees, and add one to the current node. The maximum depth of the binary tree.

Guess you like

Origin blog.csdn.net/qq_57438473/article/details/131961956