Skip to content

Commit 4f37a9d

Browse files
Merge pull request youngyangyang04#1953 from ZerenZhang2022/patch-15
Update 0222.完全二叉树的节点个数.md
2 parents 8cd0e57 + 9a4086c commit 4f37a9d

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

problems/0222.完全二叉树的节点个数.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,20 @@ class Solution:
379379
return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
380380
return self.countNodes(root.left) + self.countNodes(root.right) + 1
381381
```
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+
```
382396

383397
## Go
384398

0 commit comments

Comments
 (0)