解题思路
根据题目当中要求返回的迭代顺序,我们可以推倒出是按后序遍历的逆序进行返回的。所以我们先根据后序遍历的方式存储二叉树的节点到数组中,然后再将此数组进行逆序,最后将结果返回。
复杂度分析
O(n)
示例代码
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type Stack []*TreeNode
func (stack Stack) Len() int {
return len(stack)
}
func (stack *Stack) Push(value *TreeNode) {
*stack = append(*stack, value)
}
func (stack Stack) Top() *TreeNode {
if len(stack) == 0 {
return nil
}
return stack[len(stack)-1]
}
func (stack *Stack) Pop() *TreeNode {
theStack := *stack
if len(theStack) == 0 {
return &TreeNode{}
}
value := theStack[len(theStack)-1]
*stack = theStack[:len(theStack)-1]
return value
}
type BSTIterator struct {
content []int
}
func Constructor(root *TreeNode) BSTIterator {
iterator := BSTIterator{
content: []int{},
}
stack := new(Stack)
cur := root
for stack.Len() != 0 || cur != nil {
if cur != nil {
stack.Push(cur)
cur = cur.Right
} else {
node := stack.Pop()
iterator.content = append(iterator.content, node.Val)
cur = node.Left
}
}
for i := 0; i < len(iterator.content)/2; i++ {
iterator.content[i], iterator.content[len(iterator.content)-i-1] = iterator.content[len(iterator.content)-i-1], iterator.content[i]
}
return iterator
}
func (this *BSTIterator) Next() int {
val := this.content[0]
this.content = this.content[1:]
return val
}
func (this *BSTIterator) HasNext() bool {
return len(this.content) != 0
}