1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
type BSTIterator struct { idx int inorder []int }
func Constructor(root *TreeNode) BSTIterator { itr := BSTIterator{inorder: []int{}} dfs(root, &itr) return itr }
func (this *BSTIterator) Next() int { this.idx++ return this.inorder[this.idx-1] }
func (this *BSTIterator) HasNext() bool { return this.idx < len(this.inorder) }
func dfs(root *TreeNode, itr *BSTIterator) { if root == nil { return } dfs(root.Left, itr) itr.inorder = append(itr.inorder, root.Val) dfs(root.Right, itr) }
|