[LeetCode] Binary Search Tree Iterator 深度搜索

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Hide Tags
 Tree Stack
 

  题目的意思是给定一个bst,将全部数值 升序排列,next 从左到右输出一个值,havenext 输出时候还有未输出的值,需要做的是在class 内部维护这样的输出,同时满足一定的条件。
  方法是通过stack 来维护。
 
#include <iostream>
#include <stack>
using namespace std;

/**
 * Definition for binary tree
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class BSTIterator {
public:
    stack<TreeNode *> stk;
    BSTIterator(TreeNode *root) {
        TreeNode * node = root;
        while(node!=NULL){
            stk.push(node);
            node = node->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return stk.size()!=0;
    }

    /** @return the next smallest number */
    int next() {
        int retNum = (stk.top())->val;
        TreeNode* node = (stk.top())->right;
        stk.pop();
        while(node!=NULL){
            stk.push(node);
            node = node->left;
        }
        return retNum;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

 int main()
 {
     return 0;
 }
原文地址:https://www.cnblogs.com/Azhu/p/4334800.html