# LeetCode 104. 二叉树的最大深度(C#实现)——二叉树,BFS,DFS,递归,迭代

给定一个二叉树，找出其最大深度。

3
/ \
9  20
/  \
15   7

1、深度优先搜索，递归：对左右孩子进行DFS递归，得出最大值

2、深度优先搜索，迭代：获取最深的节点深度。根节点和当前节点深度1入栈，每次迭代中，获取并移除栈顶元素，比较当前节点深度和当前深度，取最大值，当前节点右孩子不为空的话，将右孩子和当前节点深度加一入栈，左孩子同理

3、广度优先搜索，迭代：记录二叉树的层数。根节点入队列，每次迭代，当前深度加一，循环当前队列长度，每次循环，获取并移队列顶元素，当前节点左孩子不为空，入队列，右孩子同理

    public class MaxDepthClass
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

/// <summary>
/// 深度优先搜索，递归
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public int MaxDepth(TreeNode root)
{
if (root == null) return 0;
var left = MaxDepth(root.left);
var right = MaxDepth(root.right);
return Math.Max(left, right) + 1;
}

/// <summary>
/// 广度优先搜索，迭代
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public int MaxDepthBFS(TreeNode root)
{
if (root == null) return 0;
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
var count = 0;
while (queue.Any())
{
count++;
var length = queue.Count;
for (int i = 0; i < length; i++)
{
var current = queue.Dequeue();
if (current.left != null) queue.Enqueue(current.left);
if (current.right != null) queue.Enqueue(current.right);
}
}
return count;
}

/// <summary>
/// 深度优先搜索，迭代
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public int MaxDepthDFS(TreeNode root)
{
if (root == null) return 0;
var stack = new Stack<Tuple<TreeNode, int>>();
var depth = 0;
stack.Push(new Tuple<TreeNode, int>(root, 1));
while (stack.Any())
{
var current = stack.Pop();
depth = Math.Max(depth, current.Item2);
if (current.Item1.right != null) stack.Push(new Tuple<TreeNode, int>(current.Item1.right, current.Item2 + 1));
if (current.Item1.left != null) stack.Push(new Tuple<TreeNode, int>(current.Item1.left, current.Item2 + 1));
}
return depth;
}
}

posted @ 2020-01-06 17:06  落花流水Zxxxx  阅读(148)  评论(0编辑  收藏