The maximum depth of a binary tree

Given a binary tree, find its maximum depth.

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

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

See the LeetCode website for an example.

Source: LeetCode Link: https://leetcode-cn.com/probl… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: Recursion

First, record a global result result. If root is empty, determine whether curDepth is greater than result. If root is empty, update result to curDepth. If root is empty, update result to curDepth. If root is not empty, increase CURDEPTH by 1, then recursively call root’s left and right children until the recursion is complete, returning result as the maximum depth of the tree.

package com.kaesar.leetcode; public class LeetCode_104 { public static int result = 0; public static int maxDepth(TreeNode root) { maxDepth(root, 0); return result; } public static void maxDepth(TreeNode root, int curDepth) { if (root == null) { if (curDepth > result) { result = curDepth; } return; } curDepth++; maxDepth(root.left, curDepth); maxDepth(root.right, curDepth); } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); System.out.println(maxDepth(root)); }}

【 Daily Message 】
Bumpy road, give side a warm; Wind and rain life, give yourself a smile. No big deal, in front of time, are small things.