以下是使用 TypeScript 实现二叉树最大深度的三种方法:广度优先算法(BFS) 、深度优先算法(DFS) 和 递归方法。
1. 广度优先算法(BFS)
广度优先算法通过层序遍历计算最大深度。
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
function maxDepthBFS(root: TreeNode | null): number {
if (!root) return 0;
let depth = 0;
const queue: TreeNode[] = [root];
while (queue.length) {
const levelSize = queue.length;
depth++;
for (let i = 0; i < levelSize; i++) {
const node = queue.shift()!;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return depth;
}
2. 深度优先算法(DFS)
深度优先算法通过栈模拟递归计算最大深度。
function maxDepthDFS(root: TreeNode | null): number {
if (!root) return 0;
const stack: { node: TreeNode; depth: number }[] = [{ node: root, depth: 1 }];
let maxDepth = 0;
while (stack.length) {
const { node, depth } = stack.pop()!;
maxDepth = Math.max(maxDepth, depth);
if (node.left) stack.push({ node: node.left, depth: depth + 1 });
if (node.right) stack.push({ node: node.right, depth: depth + 1 });
}
return maxDepth;
}
3. 递归方法
递归方法通过递归计算左右子树的最大深度。
function maxDepthRecursive(root: TreeNode | null): number {
if (!root) return 0;
return Math.max(maxDepthRecursive(root.left), maxDepthRecursive(root.right)) + 1;
}
测试代码
// 构建二叉树
const 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);
// 测试
console.log("BFS 最大深度:", maxDepthBFS(root)); // 输出: 3
console.log("DFS 最大深度:", maxDepthDFS(root)); // 输出: 3
console.log("递归最大深度:", maxDepthRecursive(root)); // 输出: 3
总结
- 广度优先算法(BFS) :通过层序遍历计算最大深度,适合树较宽的场景。
- 深度优先算法(DFS) :通过栈模拟递归计算最大深度,适合树较深的场景。
- 递归方法:简洁直观,但可能因递归深度过大导致栈溢出。