1、题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3 。
2、VS2019上运行
方法一:深度优先搜索
#include <iostream>
#include <algorithm>using namespace std;// 定义二叉树结点
struct TreeNode {int val;TreeNode* left;TreeNode* right;TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};class Solution {
public:int maxDepth(TreeNode* root) {if (root == nullptr) return 0;return max(maxDepth(root->left), maxDepth(root->right)) + 1;}
};int main() {// 创建二叉树TreeNode* root = new TreeNode(3);root->left = new TreeNode(9);root->right = new TreeNode(20);root->right->left = new TreeNode(15);root->right->right = new TreeNode(7);// 创建 Solution 对象Solution solution;// 调用 maxDepth 函数求解最大深度int depth = solution.maxDepth(root);// 输出结果cout << "The maximum depth of the binary tree is: " << depth << endl;return 0;
}
The maximum depth of the binary tree is: 3
3、解题思路
- 每次递归调用时,会将当前节点的深度加1。
- 在代码的最后一行 return max(maxDepth(root->left), maxDepth(root->right)) + 1; 中,+ 1 表示将当前节点的深度加1。
- 具体来说,对于每个节点,当递归到叶子节点时,会返回深度0。然后在逐层返回时,每次返回的深度都会加1,直到最终返回整个二叉树的最大深度。