algorighm/top-interview-leetcode150/binary-tree/173二叉搜索树迭代器.js

78 lines
2.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
思路根据题意在调用next()的时候我们需要按照二叉搜索树的中序遍历顺序返回结果所以可以先对BST进行中序遍历然后把遍历的结果
储存到this.nodeVals中再维护一个this.idx 来表示next 需要返回值得下标
*/
/**
* 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
*/
const BSTIterator = function (root) {
this.arr = []; // 二叉搜索树中序遍历结果
this.idx = 0; // 调用next返回得值
BSTIterator.inOrderTravers(root, this.arr); // 把中序遍历结果存入this.arr
};
/**
* @return {number}
*/
BSTIterator.prototype.next = function () {
return this.arr[this.idx++];
};
/**
* @return {boolean}
*/
BSTIterator.prototype.hasNext = function () {
// 如果this.idx 小于this.arr.lengthz则表示调用next能获取下一个元素
return this.idx < this.arr.length;
};
BSTIterator.inOrderTravers = function (root, arr) {
if (!root) return;
// 处理左子树
BSTIterator.inOrderTravers(root.left, arr);
// 将值存入数组中
arr.push(root.val);
// 处理右子树
BSTIterator.inOrderTravers(root.right, arr);
};
/**
* 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()
*/
/*
利用中序遍历迭代类维护一个栈和调用next应该打印得值
*/
// var BSTIterator = function(root) {
// this.cur = root;
// this.stack = [];
// };
// BSTIterator.prototype.next = function() {
// while (this.cur) {
// this.stack.push(this.cur);
// this.cur = this.cur.left;
// }
// this.cur = this.stack.pop();
// const ret = this.cur.val;
// this.cur = this.cur.right;
// return ret;
// };
// BSTIterator.prototype.hasNext = function() {
// return this.cur !== null || this.stack.length;
// };