很基本的问题,依旧从递归遍历或者层次广度优先遍历做起;
递归法
本题其实也要后序遍历(左右中),依然是因为要通过递归函数的返回值做计算树的高度。
按照递归三部曲,来看看如何来写。
确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
代码如下:
int getDepth(TreeNode* node)
确定终止条件:如果为空节点的话,就返回0,表示高度为0。
代码如下:
if (node == NULL) return 0;
确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
代码如下:
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);
}
};
作者:carlsun-2
链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/qiu-shu-de-zui-da-shen-du-xiang-jie-by-carlsun-2-3/
迭代法
使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合。
在二叉树中,一层一层的来遍历二叉树,记录一下遍历的层数就是二叉树的深度,如图所示:
所以这道题的迭代法就是一道模板题,可以使用二叉树层序遍历的模板来解决的。
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;
}
};
作者:carlsun-2
链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/qiu-shu-de-zui-da-shen-du-xiang-jie-by-carlsun-2-3/