501.find-mode-in-binary-search-tree.go 813 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. var cnt int = 1
  2. var max int = 0
  3. var pre int = 0
  4. var ini bool = false
  5. /**
  6. * Definition for a binary tree node.
  7. * type TreeNode struct {
  8. * Val int
  9. * Left *TreeNode
  10. * Right *TreeNode
  11. * }
  12. */
  13. func findMode(root *TreeNode) (res []int) {
  14. cnt, max, pre = 1, 0, 0 // Remember to init global variables at the beginning!
  15. ini = false
  16. if root == nil {
  17. return
  18. }
  19. inorder(root, &res)
  20. return
  21. }
  22. func inorder(root *TreeNode, res *[]int) {
  23. if root == nil {
  24. return
  25. } // Inorder traversal changes BST into increasing sequence.
  26. inorder(root.Left, res)
  27. if ini {
  28. if root.Val == pre {
  29. cnt++
  30. } else {
  31. cnt = 1
  32. }
  33. } else {
  34. ini = true
  35. }
  36. if max < cnt {
  37. *res = []int{root.Val}
  38. max = cnt
  39. } else if max == cnt {
  40. *res = append(*res, root.Val)
  41. }
  42. pre = root.Val
  43. inorder(root.Right, res)
  44. }