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.

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.

 

将非递归的中序遍历分为两部分,第一部分为将左子树上的结点全部压入栈中,第二部分为栈顶元素出栈,同时将栈顶元素的右子树上的结点压入栈中。

 

C++实现代码:

#include<iostream>
#include<new>
#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*> st;
    BSTIterator(TreeNode *root)
    {
        while(root)
        {
            st.push(root);
            root=root->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext()
    {
        return !st.empty();
    }

    /** @return the next smallest number */
    int next()
    {
        TreeNode *tmp=NULL;
        if(!st.empty())
        {
            tmp=st.top();
            st.pop();
            TreeNode *cur=tmp->right;
            while(cur)
            {
                st.push(cur);
                cur=cur->left;
            }
        }
        return tmp->val;
    }
};

void insert(TreeNode *&root,int val)
{
    if(root==NULL)
    {
        root=new TreeNode(val);
    }
    else if(val<root->val)
        insert(root->left,val);
    else
        insert(root->right,val);
}

void createBST(TreeNode *&root)
{
    int i;
    int arr[10]= {2,4,6,1,3,5,9,8,7,10};
    for(i=0; i<10; i++)
    {
        insert(root,arr[i]);
    }
}

int main()
{
    TreeNode *root=NULL;
    createBST(root);
    BSTIterator s(root);
    for(int i=0;i<10;i++)
        cout<<s.next()<<" ";
    cout<<endl;
}

看看非递归的中序遍历。。

相关文章
|
5月前
|
算法 索引
Binary Search
Binary Search “【5月更文挑战第21天】”
41 5
|
5月前
C. Binary Search
C. Binary Search
LeetCode 105. Construct Binary Tree
给定一颗二叉树的前序和顺序遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
46 0
LeetCode 105. Construct Binary Tree
LeetCode 106. Construct Binary Tree
给定一颗二叉树的中序和后续遍历,构造原二叉树。 注意:您可以假设树中不存在重复项。
68 0
LeetCode 106. Construct Binary Tree
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
二叉树(Binary Tree)的二叉链表(Binary Linked List)实现
|
算法 容器
常用查找算法 find() find_if() adjacent_find() binary_search() count() count_if()
常用查找算法 find() find_if() adjacent_find() binary_search() count() count_if()
【1043】Is It a Binary Search Tree (25 分)
【1043】Is It a Binary Search Tree (25 分) 【1043】Is It a Binary Search Tree (25 分)
118 0
|
机器学习/深度学习
1064. Complete Binary Search Tree (30)
#include #include #include using namespace std; const int maxn = 1001; vector num(maxn), cbt(maxn); int n, c...
844 0