Realization of sequential iterator__ algorithm in two-fork tree

Source: Internet
Author: User


Give the one or two-fork tree root to implement a iterator traversal, the iterator with two functions.
Boolen Hasnext () returns whether the tree also has the next inorder traversal node.
TreeNode next (), each call returns the next Inorder traversal node.

Class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode (int x) {
		val = x;


#1 easiest way to do this is to iterate through the binary tree and put it in the list. is the extra space required O (N), the disadvantage is that the initialization time is longer, the advantage is that each next is the complexity of O (1)

#2 the following non recursive sequence traversal into Hasnext and next. The worst need O (n) extra space, the advantage is to initialize O (1), the disadvantage is that the worst next complexity is O (n). Space is O (H).

public class Solution {public
    list<integer> inordertraversal (TreeNode root) {
        list<integer> result = new arraylist<integer> ();
        stack<treenode> stack = new stack<treenode> ();
        TreeNode cur = root;
        The stack was empty at the beginning but cur point to root while
        (cur!= null | |!stack.empty ()) {
            //left to the end while
            (cur!= null) {
                Stack.push (cur);
                cur = cur.left;
            Cur is empty, pop
            cur = stack.pop ();
            Result.add (cur.val);
            Turn right
            cur = cur.right;
        } The ' a ' return result

public class solution{
	private TreeNode cur;
	Private stack<treenode> Stack = new stack<treenode> ();
	Public Solution (TreeNode root) {
		cur = root;
	public Boolean Hasnext () {return
		(cur!= null | |!stack.empty ());
	Public TreeNode Next () {while
		(cur!= null) {
            stack.push (cur);
            cur = cur.left;
        TreeNode result = Stack.pop ();
        cur = result.right;
        return result;

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: 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.