mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加0222.完全二叉树的节点个数Go版本.md
This commit is contained in:
@ -437,6 +437,33 @@ func countNodes(root *TreeNode) int {
|
||||
}
|
||||
```
|
||||
|
||||
迭代法
|
||||
|
||||
```go
|
||||
func countNodes(root *TreeNode) int {
|
||||
if root == nil {
|
||||
return 0
|
||||
}
|
||||
q := list.New()
|
||||
q.PushBack(root)
|
||||
res := 0
|
||||
for q.Len() > 0 {
|
||||
n := q.Len()
|
||||
for i := 0; i < n; i++ {
|
||||
node := q.Remove(q.Front()).(*TreeNode)
|
||||
if node.Left != nil {
|
||||
q.PushBack(node.Left)
|
||||
}
|
||||
if node.Right != nil {
|
||||
q.PushBack(node.Right)
|
||||
}
|
||||
res++
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## JavaScript:
|
||||
|
Reference in New Issue
Block a user