173.二叉搜索树迭代器
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
*/
var BSTIterator = function (root) {
this.root = root
let nodes = []
const inorder = (root) => {
if(!root) {
return
}
// 左中右
inorder(root.left)
nodes.push(root.val)
inorder(root.right)
}
inorder(this.root)
this.nodes = nodes
this.curIndex = -1
};
/**
* @return {number}
*/
BSTIterator.prototype.next = function () {
this.curIndex++
return this.nodes[this.curIndex]
};
/**
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function () {
if (this.curIndex < this.nodes.length - 1) {
return true
}
return false
};
/**
* Your BSTIterator object will be instantiated and called as such:
* var obj = new BSTIterator(root)
* var param_1 = obj.next()
* var param_2 = obj.hasNext()
*/