📑 题目:173. 二叉搜索树迭代器

🚀 本题 LeetCode 传送门

题目大意

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。调用 next() 将返回二叉搜索树中的下一个最小的数。

解题思路

  • 用优先队列解决即可

代码

  1. package leetcode
  2. import (
  3. ""container/heap""
  4. ""github.com/halfrost/LeetCode-Go/structures""
  5. )
  6. // TreeNode define
  7. type TreeNode = structures.TreeNode
  8. /**
  9. * Definition for a binary tree node.
  10. * type TreeNode struct {
  11. * Val int
  12. * Left *TreeNode
  13. * Right *TreeNode
  14. * }
  15. */
  16. // BSTIterator define
  17. type BSTIterator struct {
  18. pq PriorityQueueOfInt
  19. count int
  20. }
  21. // Constructor173 define
  22. func Constructor173(root *TreeNode) BSTIterator {
  23. result, pq := []int{}, PriorityQueueOfInt{}
  24. postorder(root, &result)
  25. for _, v := range result {
  26. heap.Push(&pq, v)
  27. }
  28. bs := BSTIterator{pq: pq, count: len(result)}
  29. return bs
  30. }
  31. func postorder(root *TreeNode, output *[]int) {
  32. if root != nil {
  33. postorder(root.Left, output)
  34. postorder(root.Right, output)
  35. *output = append(*output, root.Val)
  36. }
  37. }
  38. /** @return the next smallest number */
  39. func (this *BSTIterator) Next() int {
  40. this.count--
  41. return heap.Pop(&this.pq).(int)
  42. }
  43. /** @return whether we have a next smallest number */
  44. func (this *BSTIterator) HasNext() bool {
  45. return this.count != 0
  46. }
  47. /**
  48. * Your BSTIterator object will be instantiated and called as such:
  49. * obj := Constructor(root);
  50. * param_1 := obj.Next();
  51. * param_2 := obj.HasNext();
  52. */
  53. type PriorityQueueOfInt []int
  54. func (pq PriorityQueueOfInt) Len() int {
  55. return len(pq)
  56. }
  57. func (pq PriorityQueueOfInt) Less(i, j int) bool {
  58. return pq[i] < pq[j]
  59. }
  60. func (pq PriorityQueueOfInt) Swap(i, j int) {
  61. pq[i], pq[j] = pq[j], pq[i]
  62. }
  63. func (pq *PriorityQueueOfInt) Push(x interface{}) {
  64. item := x.(int)
  65. *pq = append(*pq, item)
  66. }
  67. func (pq *PriorityQueueOfInt) Pop() interface{} {
  68. n := len(*pq)
  69. item := (*pq)[n-1]
  70. *pq = (*pq)[:n-1]
  71. return item
  72. }