0%

[Leetcode]104. Maximum Depth of Binary Tree(C++)

题目描述

题目链接:104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

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

例子

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

Note

  • A leaf is a node with no children.

解题思路

111. Minimum Depth of Binary Tree 可以用 BFS 或者 DFS 求解,代码如下:

方法一: BFS

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
std::queue<TreeNode*> q;
if (!root) return 0;
q.push(root);
int depth = 0;
while (!q.empty()) {
depth++;
std::queue<TreeNode*> next_level;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node->left) next_level.push(node->left);
if (node->right) next_level.push(node->right);
}
std::swap(q, next_level);
}

return depth;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(w)

方法二: DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int max_depth = 0;
dfs(root, 0, max_depth);

return max_depth;
}

private:
void dfs(TreeNode* node, int current_depth, int& max_depth) {
if (!node) {
return;
}
current_depth++;
if (!node->left && !node->right) {
max_depth = std::max(current_depth, max_depth);
}

dfs(node->left, current_depth, max_depth);
dfs(node->right, current_depth, max_depth);
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(h)

GitHub 代码同步地址: 104.MaximumDepthOfBinaryTree.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions