一、问题
https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 返回它的最大深度 3 。
二、GitHub实现:https://github.com/JonathanZxxxx/LeetCode/blob/master/MaxDepthClass.cs
Blog:https://www.cnblogs.com/zxxxx/
三、思路
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; } }