Update 222.完全二叉树的节点个数,添加C#递归版

This commit is contained in:
eeee0717
2023-11-18 09:48:26 +08:00
parent cfc78c3c57
commit 0843f2282d

View File

@ -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;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">