LeetCode algorithm recursive class - maximum depth of binary tree

Table of contents

104. Maximum depth of binary tree

answer:

code:

operation result:


Given a binary tree  root , return its maximum depth.

The maximum depth of a binary tree   is the number of nodes on the longest path from the root node to the furthest leaf node.

Example 1:

Input: root = [3,9,20,null,null,15,7]
 Output: 3

Example 2:

Input: root = [1,null,2]
 Output: 2

hint:

  • The number of nodes in the tree is  [0, 104] within the interval.
  • -100 <= Node.val <= 100 

answer:

  • We need to know that the core of recursion is to only focus on what this layer does and what to return . As for my next layer, I don’t need to worry about it.
  • Tags: DFS deep search
  • Termination condition: the current node is empty
  • Return value of this layer: return 0 when the node is empty, and calculate the maximum height of the left and right subtrees when the node is not empty ( recursively call the function, we don’t care how it is executed recursively in the future, this layer only needs to call the function to find Get the maximum height of the current left and right subtrees ), and add 1 to indicate the height of the current node, return this value

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;
        //递归遍历左子树
        int left=maxDepth(root.left);
        // 递归遍历右子树
        int right=maxDepth(root.right);
        // 
        return Math.max(left,right)+1;
    }
}

operation result:

 

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132273658