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; +} +```