mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0222.完全二叉树的节点个数.md
This commit is contained in:
@ -240,6 +240,71 @@ class Solution {
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
> 递归法:
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def countNodes(self, root: TreeNode) -> int:
|
||||||
|
return self.getNodesNum(root)
|
||||||
|
|
||||||
|
def getNodesNum(self, cur):
|
||||||
|
if not cur:
|
||||||
|
return 0
|
||||||
|
leftNum = self.getNodesNum(cur.left) #左
|
||||||
|
rightNum = self.getNodesNum(cur.right) #右
|
||||||
|
treeNum = leftNum + rightNum + 1 #中
|
||||||
|
return treeNum
|
||||||
|
```
|
||||||
|
|
||||||
|
> 递归法:精简版
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def countNodes(self, root: TreeNode) -> int:
|
||||||
|
if not root:
|
||||||
|
return 0
|
||||||
|
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
|
||||||
|
```
|
||||||
|
|
||||||
|
> 迭代法:
|
||||||
|
```python
|
||||||
|
import collections
|
||||||
|
class Solution:
|
||||||
|
def countNodes(self, root: TreeNode) -> int:
|
||||||
|
queue = collections.deque()
|
||||||
|
if root:
|
||||||
|
queue.append(root)
|
||||||
|
result = 0
|
||||||
|
while queue:
|
||||||
|
size = len(queue)
|
||||||
|
for i in range(size):
|
||||||
|
node = queue.popleft()
|
||||||
|
result += 1 #记录节点数量
|
||||||
|
if node.left:
|
||||||
|
queue.append(node.left)
|
||||||
|
if node.right:
|
||||||
|
queue.append(node.right)
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
> 完全二叉树
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def countNodes(self, root: TreeNode) -> int:
|
||||||
|
if not root:
|
||||||
|
return 0
|
||||||
|
left = root.left
|
||||||
|
right = root.right
|
||||||
|
leftHeight = 0 #这里初始为0是有目的的,为了下面求指数方便
|
||||||
|
rightHeight = 0
|
||||||
|
while left: #求左子树深度
|
||||||
|
left = left.left
|
||||||
|
leftHeight += 1
|
||||||
|
while right: #求右子树深度
|
||||||
|
right = right.right
|
||||||
|
rightHeight += 1
|
||||||
|
if leftHeight == rightHeight:
|
||||||
|
return (2 << leftHeight) - 1 #注意(2<<1) 相当于2^2,所以leftHeight初始为0
|
||||||
|
return self.countNodes(root.left) + self.countNodes(root.right) + 1
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user