We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 8cd0e57 + 9a4086c commit 4f37a9dCopy full SHA for 4f37a9d
problems/0222.完全二叉树的节点个数.md
@@ -379,6 +379,20 @@ class Solution:
379
return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
380
return self.countNodes(root.left) + self.countNodes(root.right) + 1
381
```
382
+完全二叉树写法2
383
+```python
384
+class Solution: # 利用完全二叉树特性
385
+ def countNodes(self, root: TreeNode) -> int:
386
+ if not root: return 0
387
+ count = 1
388
+ left = root.left; right = root.right
389
+ while left and right:
390
+ count+=1
391
+ left = left.left; right = right.right
392
+ if not left and not right: # 如果同时到底说明是满二叉树,反之则不是
393
+ return 2**count-1
394
+ return 1+self.countNodes(root.left)+self.countNodes(root.right)
395
+```
396
397
## Go
398
0 commit comments