给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
输入:root = [3,9,20,null,null,15,7] 输出:3
#include <iostream>
#include <algorithm> // 引入 std::max 函数
using namespace std; // 允许使用 std 命名空间中的名称而无需 std:: 前缀
struct TreeNode {
//储存节点
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution { //注意这里的使用方法
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0; // 如果节点为空,返回深度0
return 1 + max(maxDepth(root->left), maxDepth(root->right)); // 递归计算左右子树的最大深度,并加1
}
};
// 主函数
int main() {
// 创建一个示例二叉树:
// 1
// / \
// 2 3
//只使用第一段构造函数
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
// TreeNode root(1); // 直接创建对象,而非指针
// root.left = new TreeNode(2); // 为对象的 left 成员分配新的 TreeNode
// root.right = new TreeNode(3); // 为对象的 right 成员分配新的 TreeNode
// 创建 Solution 对象并计算二叉树的最大深度
Solution solution;
int depth = solution.maxDepth(root);
cout << "The maximum depth of the binary tree is: " << depth << endl;
// 清理分配的内存
delete root->left;
delete root->right;
delete root;
return 0;
}
/*
关于指针
int value = 10;
int* ptr2 = &value;
cout << *ptr2 << endl; // 输出:10
Solution solution; 命名一个实例
可以调用class Solution 中的函数
struct 被推荐用于被动数据结构
而 class 用于具有复杂行为的对象。
if (root == nullptr) return 0;
这个树是提前知道根的位置的
TreeNode(intx,TreeNode*left,TreeNode*right):val(x),left(left),right(right){}
构造函数 (参数列表) (初始化列表)
**使用这段构造函数的方法
TreeNode* leftChild = new TreeNode(2);
TreeNode* rightChild = new TreeNode(3);
TreeNode* root = new TreeNode(1, leftChild, rightChild);
*/