The maximum depth of a binary tree

Given a binary tree, find its maximum depth.

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

Note: Leaf nodes are nodes that have no child nodes.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/ma… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution one: recursion

First, record a global result result. Then call a recursive method, which contains two parameters, one is the current node root, one is the current depth curDepth, if root is empty, check whether curDepth is greater than result, if so, update result to curDepth. If root is not empty, curDepth is increased by 1, and the left and right children of root are recursively called until the recursion is complete. Result is returned 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)); }}Copy the code

【 Daily message 】 rough road, give around a warm; Wind and rain life, give yourself a smile. No big deal, in front of time, are small.