diff --git a/problems/0222.完全二叉树的节点个数.md b/problems/0222.完全二叉树的节点个数.md index d54f9b85..ef6e88aa 100644 --- a/problems/0222.完全二叉树的节点个数.md +++ b/problems/0222.完全二叉树的节点个数.md @@ -867,6 +867,31 @@ impl Solution { } } ``` +### C# +```C# +// 递归 +public int CountNodes(TreeNode root) +{ + if (root == null) return 0; + var left = root.left; + var right = root.right; + int leftDepth = 0, rightDepth = 0; + while (left != null) + { + left = left.left; + leftDepth++; + } + while (right != null) + { + right = right.right; + rightDepth++; + } + if (leftDepth == rightDepth) + return (int)Math.Pow(2, leftDepth+1) - 1; + return CountNodes(root.left) + CountNodes(root.right) + 1; + +} +```