The maximum depth of leetcode-0104 binary tree

Time:2021-6-11

Title addresshttps://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

1. Recursion

Time complexity O (n) space complexity O (H), space complexity is mainly used for recursive stack depth H
It’s very simple to use recursion to solve the problem locally. The first condition of recursion termination is recursion to the current node is null.

var maxDepth = function(root) {
  if (root === null) {
    return 0
  }
  return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};

2. Depth first search

DFS is generally implemented in the form of stack, with time complexity O (n) and space complexity O (n). In this problem, each location of the stack stores an array containing two elements. The first element is the current node, and the second element is the corresponding depth of the current node. In this way, we can record the depth of each node, which is convenient for traversing to the next element. Because this problem has no traversal sequence requirements, only requires each node to traverse, so DFS and BFS are both feasible.

var maxDepth = function(root) {
    const stack = [];
    if (root === null) return 0;
    stack.push([root, 1]);
    let depth = 0;
    while (stack.length > 0) {
        const [node, curDepth] = stack.pop();
        depth = Math.max(depth, curDepth);
        node.left && stack.push([node.left, curDepth + 1]);
        node.right && stack.push([node.right, curDepth + 1]);
    }
    return depth;
};

3. Breadth first search

BFS is usually implemented in the form of queue with time complexity O (n) and space complexity O (n)

var maxDepth = function(root) {
    const queue = [];
    if (root == null) return 0;
    let depth = 0;
    queue.push([root, 1]);
    while (queue.length > 0) {
        const [node, curDepth] = queue.shift();
        depth = Math.max(depth, curDepth);
        node.left && queue.push([node.left, curDepth + 1]);
        node.right && queue.push([node.right, curDepth + 1]);
    }
    return depth;
};

For more questions about leetcode and data structure, please pay attention to myGitHub, find a star