二叉树的遍历方法分为深度优先遍历和广度优先遍历,深度优先遍历又分为先序遍历中序遍历和后序遍历。
深度优先遍历计算
深度优先遍历主要采用递归的方式计算,把要计算的二叉树分为左子树和右子树,每递一次深度加1,最后比较左子树和右子树的深度取最大+1
实现
我们先定义一个二叉树结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
接下来的二叉树用的都是这个结构体。
通过递归计算左右子树的最大深度,逐层向上返回结果
- 终止条件:空节点深度为 0。
- 递归逻辑:当前节点深度 = max(左子树深度, 右子树深度) + 1。
#include <algorithm>
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0; // 空节点深度为0
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return std::max(left, right) + 1; // 返回较大子树深度+1
}
广度优先遍历计算
核心原理
广度优先遍历采用迭代的方式实现,通过层序遍历统计树的层数(即深度)
- 使用队列逐层遍历节点。
- 每遍历完一层,深度加 1。
实现
#include <queue>
int maxDepth(TreeNode* root) {
if (!root) return 0;
std::queue<TreeNode*> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
int size = q.size();
depth++; // 每层深度+1
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front();
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return depth;
}
测试用例
int main() {
// 构建示例二叉树:深度为3
// 1
// / \
// 2 3
// / \
// 4 5
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(5);
// 测试递归法
std::cout << "递归法深度: " << maxDepth(root) << std::endl; // 输出3
// 测试迭代法
std::cout << "迭代法深度: " << maxDepth(root) << std::endl; // 输出3
// 释放内存(实际开发中建议用智能指针)
delete root->right->right;
delete root->right->left;
delete root->right;
delete root->left;
delete root;
return 0;
}