输入一棵二叉树的根节点,求该树的深度。从根节点到叶结点以此经过的节点(含根节点、叶节点)形成树的一条路径,最长路径的长度为树的深度。
### 思路一: DFS
1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int。
2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0.
3. 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值,再+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);
}
};
### 思路二:迭代法BFS
1. 首先要定义一个queue来存放二叉树每一层的节点
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;
}
};