mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 222.完全二叉树的节点个数,添加C#递归版
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user