mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
添加0222.完全二叉树的节点个数迭代解法Java代码
This commit is contained in:
@ -204,7 +204,27 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
// 迭代法
|
||||||
|
public int countNodes(TreeNode root) {
|
||||||
|
if (root == null) return 0;
|
||||||
|
Queue<TreeNode> queue = new LinkedList<>();
|
||||||
|
queue.offer(root);
|
||||||
|
int result = 0;
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
int size = queue.size();
|
||||||
|
while (size -- > 0) {
|
||||||
|
TreeNode cur = queue.poll();
|
||||||
|
result++;
|
||||||
|
if (cur.left != null) queue.offer(cur.left);
|
||||||
|
if (cur.right != null) queue.offer(cur.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
```java
|
```java
|
||||||
class Solution {
|
class Solution {
|
||||||
/**
|
/**
|
||||||
|
Reference in New Issue
Block a user