222.count-complete-tree-nodes.go 460 B

1234567891011121314151617181920212223242526
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func countNodes(root *TreeNode) (cnt int) {
  10. if root == nil {
  11. return
  12. }
  13. lvs := []*TreeNode{root}
  14. for n := len(lvs); n != 0; n = len(lvs) {
  15. node := lvs[n-1]
  16. lvs = lvs[:n-1]
  17. cnt++
  18. if node.Left != nil {
  19. lvs = append(lvs, node.Left)
  20. }
  21. if node.Right != nil {
  22. lvs = append(lvs, node.Right)
  23. }
  24. }
  25. return
  26. }