下面是一个完整的C#程序,演示如何计算二叉树的深度,包括递归和迭代两种实现方法。
using System;
using System.Collections.Generic;
// 二叉树节点定义
public class TreeNode
{
public int Val { get; set; }
public TreeNode Left { get; set; }
public TreeNode Right { get; set; }
public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
{
Val = val;
Left = left;
Right = right;
}
}
public class BinaryTreeDepth
{
// 递归方法求二叉树深度
public static int GetDepthRecursive(TreeNode root)
{
if (root == null)
return 0;
int leftDepth = GetDepthRecursive(root.Left);
int rightDepth = GetDepthRecursive(root.Right);
return Math.Max(leftDepth, rightDepth) + 1;
}
// 迭代方法求二叉树深度(使用队列进行层次遍历)
public static int GetDepthIterative(TreeNode root)
{
if (root == null)
return 0;
Queue<TreeNode> queue = new Queue<TreeNode>();
queue.Enqueue(root);
int depth = 0;
while (queue.Count > 0)
{
int levelSize = queue.Count;
depth++;
for (int i = 0; i < levelSize; i++)
{
TreeNode currentNode = queue.Dequeue();
if (currentNode.Left != null)
queue.Enqueue(currentNode.Left);
if (currentNode.Right != null)
queue.Enqueue(currentNode.Right);
}
}
return depth;
}
// 创建示例二叉树
public static TreeNode CreateSampleTree()
{
// 创建以下结构的二叉树:
// 1
// / \
// 2 3
// / \ \
// 4 5 6
// /
// 7
return new TreeNode(1,
new TreeNode(2,
new TreeNode(4),
new TreeNode(5,
new TreeNode(7),
null)
),
new TreeNode(3,
null,
new TreeNode(6)
)
);
}
public static void Main(string[] args)
{
TreeNode root = CreateSampleTree();
// 使用递归方法计算深度
int recursiveDepth = GetDepthRecursive(root);
Console.WriteLine($"递归方法计算的二叉树深度: {recursiveDepth}");
// 使用迭代方法计算深度
int iterativeDepth = GetDepthIterative(root);
Console.WriteLine($"迭代方法计算的二叉树深度: {iterativeDepth}");
// 验证两种方法结果是否一致
Console.WriteLine($"两种方法结果一致: {recursiveDepth == iterativeDepth}");
// 绘制二叉树结构
Console.WriteLine("\n二叉树结构:");
PrintTree(root, 0);
}
// 辅助方法:打印二叉树结构
public static void PrintTree(TreeNode node, int depth)
{
if (node == null)
return;
PrintTree(node.Right, depth + 1);
Console.WriteLine(new string(' ', depth * 4) + node.Val);
PrintTree(node.Left, depth + 1);
}
}
代码说明
-
TreeNode类:定义了二叉树节点的基本结构,包含值、左子节点和右子节点。
-
递归方法(GetDepthRecursive):
-
如果节点为空,返回深度0
-
否则,递归计算左子树和右子树的深度
-
返回左右子树深度的最大值加1(当前节点所在层)
-
-
迭代方法(GetDepthIterative):
-
使用队列进行广度优先遍历(层次遍历)
-
每次处理一层的所有节点,深度加1
-
直到队列为空,返回累计的深度值
-
-
示例和测试:
-
创建了一个示例二叉树
-
使用两种方法计算深度并比较结果
-
打印二叉树结构以便可视化
-
复杂度分析
-
时间复杂度:两种方法都是O(n),其中n是二叉树中的节点数
-
空间复杂度:
-
递归方法:最坏情况下O(n)(当树退化为链表时)
-
迭代方法:最坏情况下O(n)(当树为完全二叉树时)
-