Update 222.完全二叉树的节点个数,添加C#递归版
This commit is contained in:
parent
cfc78c3c57
commit
0843f2282d
|
|
@ -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">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue