上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode* root) {
}
int next() {
}
bool hasNext() {
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
golang 解法, 执行用时: 16 ms, 内存消耗: 9.5 MB, 提交时间: 2022-11-10 17:22:56
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type BSTIterator struct {
stack []*TreeNode
cur *TreeNode
}
func Constructor(root *TreeNode) BSTIterator {
return BSTIterator{cur: root}
}
func (it *BSTIterator) Next() int {
for node := it.cur; node != nil; node = node.Left {
it.stack = append(it.stack, node)
}
it.cur, it.stack = it.stack[len(it.stack)-1], it.stack[:len(it.stack)-1]
val := it.cur.Val
it.cur = it.cur.Right
return val
}
func (it *BSTIterator) HasNext() bool {
return it.cur != nil || len(it.stack) > 0
}
/**
* Your BSTIterator object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Next();
* param_2 := obj.HasNext();
*/
python3 解法, 执行用时: 192 ms, 内存消耗: 21 MB, 提交时间: 2022-11-10 17:20:08
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: TreeNode):
self.arr = []
self.inorder(root)
def inorder(self, node: TreeNode):
if node != None:
self.inorder(node.left)
self.arr.append(node.val)
self.inorder(node.right)
def next(self) -> int:
val = self.arr[0]
self.arr = self.arr[1:]
return val
def hasNext(self) -> bool:
return len(self.arr) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
golang 解法, 执行用时: 36 ms, 内存消耗: 9.4 MB, 提交时间: 2022-11-10 17:15:45
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type BSTIterator struct {
arr []int
}
func Constructor(root *TreeNode) (it BSTIterator) {
it.inorder(root)
return
}
func (it *BSTIterator) inorder(node *TreeNode) {
if node == nil {
return
}
it.inorder(node.Left)
it.arr = append(it.arr, node.Val)
it.inorder(node.Right)
}
func (it *BSTIterator) Next() int {
val := it.arr[0]
it.arr = it.arr[1:]
return val
}
func (it *BSTIterator) HasNext() bool {
return len(it.arr) > 0
}
/**
* Your BSTIterator object will be instantiated and called as such:
* obj := Constructor(root);
* param_1 := obj.Next();
* param_2 := obj.HasNext();
*/