From 3ffca338cafa5ba72d81048d762211488f7d19f7 Mon Sep 17 00:00:00 2001 From: eeee0717 <70054568+eeee0717@users.noreply.github.com> Date: Thu, 16 Nov 2023 09:12:06 +0800 Subject: [PATCH] =?UTF-8?q?Update104.=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E6=9C=80=E5=A4=A7=E6=B7=B1=E5=BA=A6=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?C#=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0104.二叉树的最大深度.md | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/0104.二叉树的最大深度.md b/problems/0104.二叉树的最大深度.md index 05044375..ab3ce52e 100644 --- a/problems/0104.二叉树的最大深度.md +++ b/problems/0104.二叉树的最大深度.md @@ -1022,6 +1022,61 @@ impl Solution { max_depth } ``` +### C# +```C# +// 递归法 +public int MaxDepth(TreeNode root) { + if(root == null) return 0; + + int leftDepth = MaxDepth(root.left); + int rightDepth = MaxDepth(root.right); + + return 1 + Math.Max(leftDepth, rightDepth); +} +``` +```C# +// 前序遍历 +int result = 0; +public int MaxDepth(TreeNode root) +{ + if (root == null) return result; + GetDepth(root, 1); + return result; +} +public void GetDepth(TreeNode root, int depth) +{ + result = depth > result ? depth : result; + if (root.left == null && root.right == null) return; + + if (root.left != null) + GetDepth(root.left, depth + 1); + if (root.right != null) + GetDepth(root.right, depth + 1); + return; +} +``` +```C# +// 迭代法 +public int MaxDepth(TreeNode root) +{ + int depth = 0; + Queue que = new(); + if (root == null) return depth; + que.Enqueue(root); + while (que.Count != 0) + { + int size = que.Count; + depth++; + for (int i = 0; i < size; i++) + { + var node = que.Dequeue(); + if (node.left != null) que.Enqueue(node.left); + if (node.right != null) que.Enqueue(node.right); + } + } + return depth; +} +```