Java for Leetcode 173 Binary Search Tree Iterator

Source: Internet
Author: User

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

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

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

Problem Solving Ideas:

In fact, according to the order of the sequence traversal, there are two ways to realize:

First, the construction of BST directly under the preprocessing, the construction of a list in accordance with the sequence traversal, each read the elements of the list.

Second, do not pre-processing, according to the idea of sequential traversal using stack dynamic processing

Here we realize the idea of two:

public class Bstiterator {private stack<treenode> stack=new stack<treenode> ();p ublic bstiterator (TreeNode Root) {if (root = null) pushleft (root);} /** @return Whether we have a next smallest number */public Boolean hasnext () {return!stack.isempty ();} /** @return The next smallest number */public int next () {TreeNode top = Stack.peek (); Stack.pop (); if (top.right!=null) PUSHL EFT (top.right); return top.val;} public void Pushleft (TreeNode root) {Stack.push (root); TreeNode roottemp = Root.left;while (roottemp! = null) {Stack.push (roottemp); roottemp = Roottemp.left;}}}

Java for Leetcode 173 Binary Search Tree Iterator

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.