leetcode 104 二叉树的最大深度
思路
1、递归法
① 确定递归函数的参数和返回值:
参数就是 传入树的根节点,返回值就是返回这棵树的深度,所以 返回值为int类型。
int getDepth(TreeNode* node)
②确定终止条件:
如果为空节点的话,就返回0,表示高度为0。
if (node == NULL) return 0;
③确定每层递归的逻辑:
先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 ( 加1是因为算上当前节点),就是目前节点为根节点的树的深度。
按照后序遍历(左、右、中)去遍历二叉树。
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
完整代码:
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
当然,上一篇文章不是说了可以化繁为简嘛~
精简代码如下:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
当然,这在逻辑上也看不出来是二叉树的哪种遍历了。
2、迭代法
使用迭代法的话, 层序遍历是最为合适,因为最大的深度就是二叉树的层数。、
直接抄前面博客写的二叉树层序模板就行了 。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth++; // 记录深度
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
学会了求解二叉树的最大深度,也就可以求解N叉树的最大深度。
leetcode 559 N叉树的最大深度
思路
不用多说,跟leetcode 104一样,递归迭代都可以。迭代法还是采用层序遍历。
我就直接贴代码了。
1、递归法
class Solution {
public:
int maxDepth(Node* root) {
if (root == 0) return 0;
int depth = 0;
for (int i = 0; i < root->children.size(); i++) {
depth = max (depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
2、迭代法
class Solution {
public:
int maxDepth(Node* root) {
queue<Node*> que;
if (root != NULL) que.push(root);
int depth = 0;
while (!que.empty()) {
int size = que.size();
vector<int> vec;
depth++; // 记录深度
for (int i = 0; i < size; i++) {
Node* node = que.front();
que.pop();
for (int j = 0; j < node->children.size(); j++) {
if (node->children[j]) que.push(node->children[j]);
}
}
}
return depth;
}
};
学会这些题,大概就理解 自古真情留不住,唯有套路得人心了吧~