LeetCode刷题 Day16

80 阅读2分钟

LeetCode刷题 Day16

104. Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

  Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

思路:

  • 因为树的高度和深度相等, 所以可以通过计算高度得到深度

代码:

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

时间复杂度: O(N) 空间复杂度: O(logN)


111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 2

Example 2:

Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5

方法1 BFS:

  • BFS 是比较直观的一个解法,因为首次遇到的 !root.left && !root.right 节点即可决定最小深度.

方法2 DFS:

  • 当left为空而right不为空的时候, 需要计算right的最小深度
  • 同理, 当right为空而left不为空的时候, 需要计算left的最小深度

代码:

var minDepth = function(root) {
    if (!root) return 0;
    if (!root.left && root.right) return 1 + minDepth(root.right);
    if (root.left && !root.right) return 1 + minDepth(root.left);
    
    return 1 + Math.min(minDepth(root.left), minDepth(root.right));
};

时间复杂度: O(N), 空间复杂度: O(logN)


222. Count Complete Tree Nodes

Given the root of a complete binary tree, return the number of the nodes in the tree.

According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Design an algorithm that runs in less than O(n) time complexity.

  Example 1:

Input: root = [1,2,3,4,5,6]
Output: 6

Example 2:

Input: root = []
Output: 0

思路:

  • 是一个非常直接的算节点个数的题目,没遍历到一个节点就 + 1

代码:

var countNodes = function(root) {
    if (!root) return 0;
    
    return 1 + countNodes(root.left) + countNodes(root.right);
};

时间复杂度: O(N), 空间复杂度:O(logN)