@@ -1022,6 +1022,61 @@ impl Solution {
1022
1022
max_depth
1023
1023
}
1024
1024
```
1025
+ ### C#
1026
+ ``` C#
1027
+ // 递归法
1028
+ public int MaxDepth (TreeNode root ) {
1029
+ if (root == null ) return 0 ;
1030
+
1031
+ int leftDepth = MaxDepth (root .left );
1032
+ int rightDepth = MaxDepth (root .right );
1033
+
1034
+ return 1 + Math .Max (leftDepth , rightDepth );
1035
+ }
1036
+ ```
1037
+ ``` C#
1038
+ // 前序遍历
1039
+ int result = 0 ;
1040
+ public int MaxDepth (TreeNode root )
1041
+ {
1042
+ if (root == null ) return result ;
1043
+ GetDepth (root , 1 );
1044
+ return result ;
1045
+ }
1046
+ public void GetDepth (TreeNode root , int depth )
1047
+ {
1048
+ result = depth > result ? depth : result ;
1049
+ if (root .left == null && root .right == null ) return ;
1050
+
1051
+ if (root .left != null )
1052
+ GetDepth (root .left , depth + 1 );
1053
+ if (root .right != null )
1054
+ GetDepth (root .right , depth + 1 );
1055
+ return ;
1056
+ }
1057
+ ```
1058
+ ``` C#
1059
+ // 迭代法
1060
+ public int MaxDepth (TreeNode root )
1061
+ {
1062
+ int depth = 0 ;
1063
+ Queue < TreeNode > que = new ();
1064
+ if (root == null ) return depth ;
1065
+ que .Enqueue (root );
1066
+ while (que .Count != 0 )
1067
+ {
1068
+ int size = que .Count ;
1069
+ depth ++ ;
1070
+ for (int i = 0 ; i < size ; i ++ )
1071
+ {
1072
+ var node = que .Dequeue ();
1073
+ if (node .left != null ) que .Enqueue (node .left );
1074
+ if (node .right != null ) que .Enqueue (node .right );
1075
+ }
1076
+ }
1077
+ return depth ;
1078
+ }
1079
+ ```
1025
1080
1026
1081
<p align =" center " >
1027
1082
<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
0 commit comments