前言:又虚度了个周某,被自己浪哭了。
1. 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 farthest leaf node.
题意:
即求二叉树的深度
思路:
因为结构体里有左右两个节点的指针,设定一个保存结果的值,初始化为1,每往左或者右扫一个节点,这个值+1。然后用BFS或者DFS从根节点不断遍历下去即可。
操作:
BFS和DFS的代码基本一样,只不过BFS用队列,DFS用栈
2. 代码
非递归BFS:
class Solution {
public:
int bfs(struct TreeNode* root) {
int result = 1;
queue<pair<TreeNode*, int>> q;
q.push({root, 1});
while (!q.empty()) {
TreeNode *cur = q.front().first;
int dep = q.front().second;
q.pop();
if (dep > result) result = dep;
if (cur->left) q.push({cur->left, dep+1});
if (cur->right) q.push({cur->right, dep+1});
}
return result;
}
int maxDepth(TreeNode* root) {
if (root) {
return bfs(root);
}
return 0;
}
};
非递归DFS:
class Solution {
public:
int dfs(struct TreeNode* root) {
int result = 1;
stack<pair<TreeNode*, int>> s;
s.push({root, 1});
while (!s.empty()) {
TreeNode *cur = s.top().first;
int dep = s.top().second;
s.pop();
if (dep > result) result = dep;
if (cur->left) s.push({cur->left, dep+1});
if (cur->right) s.push({cur->right, dep+1});
}
return result;
}
int maxDepth(TreeNode* root) {
if (root) {
return dfs(root);
}
return 0;
}
};
3.递归解
作为一道水题。。。DFS递归版的代码是真滴简略:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root) return 1+ max(maxDepth(root->left), maxDepth(root->right));
return 0;
}
};