mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-12 21:50:49 +08:00
Update 0222.完全二叉树的节点个数.md
This commit is contained in:
@ -393,6 +393,20 @@ class Solution: # 利用完全二叉树特性
|
|||||||
return 2**count-1
|
return 2**count-1
|
||||||
return 1+self.countNodes(root.left)+self.countNodes(root.right)
|
return 1+self.countNodes(root.left)+self.countNodes(root.right)
|
||||||
```
|
```
|
||||||
|
完全二叉树写法3
|
||||||
|
```python
|
||||||
|
class Solution: # 利用完全二叉树特性
|
||||||
|
def countNodes(self, root: TreeNode) -> int:
|
||||||
|
if not root: return 0
|
||||||
|
count = 0
|
||||||
|
left = root.left; right = root.right
|
||||||
|
while left and right:
|
||||||
|
count+=1
|
||||||
|
left = left.left; right = right.right
|
||||||
|
if not left and not right: # 如果同时到底说明是满二叉树,反之则不是
|
||||||
|
return (2<<count)-1
|
||||||
|
return 1+self.countNodes(root.left)+self.countNodes(root.right)
|
||||||
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user