104. 二叉树的最大深度

leetCode

# BFS

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    let maxDepth = 0
    // 树为空的时候
    if (root === null) return maxDepth
    // 定义一个队列
    let queue = []
    let count = 0
    queue.push(root)
    while (queue.length > 0) {
        // 获取这一层的长度
        let size= queue.length
        // 遍历这一层的内容
        while (size > 0){
            let node = queue.shift()
            size--
            if(node.left || node.right) {
                if(node.left !== null) queue.push(node.left)
                if(node.right !== null) queue.push(node.right)
            }
        }
        maxDepth++
    }
    return maxDepth
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# DFS

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    // 树为空的时候
    if (root === null) return 0
    let leftDep = maxDepth(root.left)
    let rightDep = maxDepth(root.right)
    return Math.max(leftDep, rightDep)+1
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
更新时间: 2022-03-25 17:04