104. The maximum depth of the binary tree (java implementation) --LeetCode

Article Directory

topic:

Given a binary tree, find its maximum depth.

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

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

Example:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Return its maximum depth 3.

Solution 1: Recursion

    /**
     * 思路
     * 遍历树
     * 不断的递归,记录左右节点的深度,返回其中最大的
     */
    public int maxDepth(TreeNode root) {
    
    
        int maxDepth = recursive(root, 1);
        return maxDepth;
    }

    private int recursive(TreeNode root, int maxDepth) {
    
    
        if (root == null) return maxDepth-1;
        int l_max = recursive(root.left, maxDepth + 1);
        int r_max = recursive(root.right, maxDepth + 1);
        return Math.max(l_max, r_max);
    }

Time complexity: On

Space complexity: O1
Insert picture description here

    /**
     * 思路:
     * 获取左右节点中深度最大的那个
     * 到了叶子节点0,0返回1
     * 递归这个过程
     */
    public int maxDepth(TreeNode root) {
    
    
        if (root==null)return 0;
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        return Math.max(leftDepth,rightDepth)+1;
    }

Time complexity: On

Space complexity: O1
Insert picture description here

    /**
     * 思路
     * 全局max,记录当前depth
     * 比较depth max
     */
    int max;
    public int maxDepth(TreeNode root) {
    
    
        recursive(root,1);
        return max;
    }

    private void recursive(TreeNode root, int depth) {
    
    
        if (root==null)return;
        max=depth>max?depth:max;
        recursive(root.left,depth+1);
        recursive(root.right,depth+1);
    }

Time complexity: On

Space complexity: O1
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/112967368