题意:

image.png

解题思路:

  1. next()方法做两件事:
  2. 1. 把栈顶节点出栈,并把节点值返回
  3. 2. 把栈顶节点右子树的最左侧分支入栈

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class BSTIterator {
  11. /**
  12. * @param TreeNode $root
  13. */
  14. private $stack = [];
  15. function __construct($root) {
  16. while ($root != null) {
  17. $this->stack[] = $root;
  18. $root = $root->left;
  19. }
  20. }
  21. /**
  22. * @return the next smallest number
  23. * @return Integer
  24. */
  25. function next() {
  26. $root = array_pop($this->stack);
  27. $val = $root->val;
  28. $root = $root->right;
  29. while ($root != null) {
  30. $this->stack[] = $root;
  31. $root = $root->left;
  32. }
  33. return $val;
  34. }
  35. /**
  36. * @return whether we have a next smallest number
  37. * @return Boolean
  38. */
  39. function hasNext() {
  40. return !empty($this->stack);
  41. }
  42. }
  43. /**
  44. * Your BSTIterator object will be instantiated and called as such:
  45. * $obj = BSTIterator($root);
  46. * $ret_1 = $obj->next();
  47. * $ret_2 = $obj->hasNext();
  48. */

go代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. type BSTIterator struct {
  10. stack []*TreeNode
  11. }
  12. func Constructor(root *TreeNode) BSTIterator {
  13. BST := []*TreeNode{}
  14. for root != nil {
  15. BST = append(BST, root)
  16. root = root.Left
  17. }
  18. return BSTIterator {
  19. stack: BST,
  20. }
  21. }
  22. /** @return the next smallest number */
  23. func (this *BSTIterator) Next() int {
  24. n := len(this.stack)
  25. cur := this.stack[n - 1]
  26. this.stack = this.stack[:n-1]
  27. root := cur.Right
  28. for root != nil {
  29. this.stack = append(this.stack, root)
  30. root = root.Left
  31. }
  32. return cur.Val
  33. }
  34. /** @return whether we have a next smallest number */
  35. func (this *BSTIterator) HasNext() bool {
  36. return len(this.stack) > 0
  37. }
  38. /**
  39. * Your BSTIterator object will be instantiated and called as such:
  40. * obj := Constructor(root);
  41. * param_1 := obj.Next();
  42. * param_2 := obj.HasNext();
  43. */