[LeetCode] 104. The maximum depth of the binary tree (same sword refers to Offer 55-I)

1. 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:

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

    3
   / \
  9  20
    /  \
   15   7

Return its maximum depth 3.

Two, solve

1. Recursion

Idea: It's relatively simple, just look at the code directly.
Code:

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root == null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

Time complexity: O (n) O(n)O ( n )
space complexity: O (n) O(n)O ( n )

2、BFS

Idea: It is modified according to the BFS template.
Code:

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        int depth = 0;
        if (root == null) return depth;
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()) {
    
    
            int levelSize = q.size();
            for (int i = 0; i < levelSize; i++) {
    
    
                TreeNode node = q.poll();
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
            depth++;
        }
        return depth;
    }
}

Time complexity: O (n) O(n)O ( n )
space complexity: O (n) O(n)O ( n )

Three, reference

1. Interview Question 55-I. The depth of the binary tree (post-order traversal, layer-order traversal, clear illustration)
2. Recursion, BFS, DFS 3 solutions
3. Two Java Iterative solution DFS and BFS

Guess you like

Origin blog.csdn.net/HeavenDan/article/details/110920860