Given a binary search tree, print the elements in-order iteratively without using recursion.

Note:
Before you attempt this problem, you might want to try coding a pre-order traversal iterative solution first, because it is easier. On the other hand, coding a post-order iterative version is a challenge. See my post: Binary Tree Post-Order Traversal Iterative Solution for more details and an in-depth analysis of the problem.

We know the elements can be printed in-order easily using recursion, as follow:

 
1
2
3
4
5
6
voidin_order_traversal(BinaryTree *p){
  if(!p)return;
  in_order_traversal(p->left);
  cout<<p->data;
  in_order_traversal(p->right);
}

Excessive recursive function calls may cause memory to run out of stack space and extra overhead. Since the depth of a balanced binary search tree is about lg(n), you might not worry about running out of stack space, even when you have a million of elements. But what if the tree is not balanced? Then you are asking for trouble, because in the worst case the height of the tree may go up to n. If that is the case, stack space will eventually run out and your program will crash.

To solve this issue, we need to develop an iterative solution. The idea is easy, we need a stack to store previous nodes, and a visited flag for each node is needed to record if the node has been visited before. When a node is traversed for the second time, its value will be printed. After its value is printed, we push its right child and continue from there.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
voidin_order_traversal_iterative(BinaryTree *root){
  stack<BinaryTree*>s;
  s.push(root);
  while(!s.empty()){
    BinaryTree *top=s.top();
    if(top!=NULL){
      if(!top->visited){
        s.push(top->left);
      }else{
        cout<<top->data<<" ";
        s.pop();
        s.push(top->right);
      }
    }else{
      s.pop();
      if(!s.empty())
        s.top()->visited=true;
    }
  }
}

Alternative Solution:
The above solution requires modification to the original BST data structure (ie, adding a visited flag). The other solution which doesn’t modify the original structure is with the help of a current pointer in addition of a stack.

First, the current pointer is initialized to the root. Keep traversing to its left child while pushing visited nodes onto the stack. When you reach a NULL node (ie, you’ve reached a leaf node), you would pop off an element from the stack and set it to current. Now is the time to print current’s value. Then, current is set to its right child and repeat the process again. When the stack is empty, this means you’re done printing.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
voidin_order_traversal_iterative(BinaryTree *root){
  stack<BinaryTree*>s;
  BinaryTree *current=root;
  booldone=false;
  while(!done){
    if(current){
      s.push(current);
      current=current->left;
    }else{
      if(s.empty()){
        done=true;
      }else{
        current=s.top();
        s.pop();
        cout<<current->data<<" ";
        current=current->right;
      }
    }
  }
}

We can even do better by refactoring the above code. The refactoring relies on one important observation:

The last traversed node must not have a right child.

Why this is true? To prove this, we assume the opposite, that is: the last traversed node has a right child. This is certainly incorrect, as in-order traversal would have to traverse its right child next before the traversal is done. Since this is incorrect, the last traversed node must not have a right child by contradiction.

Below is the refactored code:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
voidin_order_traversal_iterative(BinaryTree *root){
  stack<BinaryTree*>s;
  BinaryTree *current=root;
  while(!s.empty()||current){
    if(current){
      s.push(current);
      current=current->left;
    }else{
      current=s.top();
      s.pop();
      cout<<current->data<<" ";
      current=current->right;
    }
  }
}

threaded tree, with the special threading links shown by dashed arrows. A threaded binary tree makes it possible to traverse the values in the binary tree via a linear traversal that is more rapid than a recursive in-order traversal.

Further Thoughts:
The above solutions require the help of a stack to do in-order traversal. Is it possible to do in-order traversal without a stack?

The answer is yes, it’s possible. There’s 2 possible ways that I know of:

    1. By adding a parent pointer to the data structure, this allows us to return to a node’s parent (Credits to my friend who provided this solution to me). To determine when to print a node’s value, we would have to determine when it’s returned from. If it’s returned from its left child, then you would print its value then traverse to its right child, on the other hand if it’s returned from its right child, you would traverse up one level to its parent.
    2. By using a Threaded Binary Tree. Read the article: Threaded Binary Tree on Wikipedia for more information.
 public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> st = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
if(root == null) return result;
boolean fin = false;
while(!fin){
if(root != null){
st.push(root);
root = root.left;
}else{
if(st.size() == 0){
fin = true;
}else{
root = st.pop();
result.add(root.val);
root = root.right;
}
}
}
return result;
}
}

这个代码是错误的:

 public List<Integer> inorderTraversal(TreeNode root) {
// write your code here
LinkedList<TreeNode> stack = new LinkedList<TreeNode> (); //stack
List<Integer> result = new ArrayList<Integer> ();
if(root == null) return result;
stack.push(root);
while(!stack.isEmpty()){
TreeNode tmp = stack.peek();
if(tmp.left != null) stack.push(tmp.left);
else{
tmp = stack.pop();
result.add(tmp.val);
if(tmp.right != null) stack.push(tmp.right);
}
}
return result;
}

会在最后一个root 和其left leaf之间无限循环。

Binary Search Tree In-Order Traversal Iterative Solution的更多相关文章

  1. [Leetcode][JAVA] Recover Binary Search Tree (Morris Inorder Traversal)

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  2. [Swift]LeetCode1008. 先序遍历构造二叉树 | Construct Binary Search Tree from Preorder Traversal

    Return the root node of a binary search tree that matches the given preorder traversal. (Recall that ...

  3. LeetCode 1008. Construct Binary Search Tree from Preorder Traversal

    原题链接在这里:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 题目: Retu ...

  4. 【leetcode】1008. Construct Binary Search Tree from Preorder Traversal

    题目如下: Return the root node of a binary search tree that matches the given preorder traversal. (Recal ...

  5. 【LeetCode】 99. Recover Binary Search Tree [Hard] [Morris Traversal] [Tree]

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  6. 【LeetCode】1008. Construct Binary Search Tree from Preorder Traversal 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  7. leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)

    https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...

  8. 算法与数据结构基础 - 二叉查找树(Binary Search Tree)

    二叉查找树基础 二叉查找树(BST)满足这样的性质,或是一颗空树:或左子树节点值小于根节点值.右子树节点值大于根节点值,左右子树也分别满足这个性质. 利用这个性质,可以迭代(iterative)或递归 ...

  9. LeetCode解题报告—— Unique Binary Search Trees & Binary Tree Level Order Traversal & Binary Tree Zigzag Level Order Traversal

    1. Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees) that ...

随机推荐

  1. Jquery 学习一

    一.jQuery概述 1.Javascript代码库 在早期的项目开发中都是使用Javascript原生代码,一行一行编写.但是Javascript自身存在3个弊端: ① 复杂的DOM操作 ② 不一致 ...

  2. java中的异常处理机制_函数覆盖时的异常特点

    /*注意:异常声明在函数上 异常在子父类覆盖时的体现1.子类在覆盖父类时,如果父类的方法抛出异常,那么子类的覆盖方法,只能抛出父类的异常或者异常的子类2.如果父类方法抛出多个异常,那么子类在覆盖该方法 ...

  3. Java中的toString()方法

    Java中的toString()方法 目录 Java中的toString()方法 1.    对象的toString方法 2.    基本类型的toString方法 3.    数组的toString ...

  4. 济南学习 Day2 T2 am

    [问题描述]有N个数,随机选择一段区间,如果这段区间的所有数的平均值在[l,r]中则你比较厉害.求你比较厉害的概率.[输入格式]第一行有三个数N,l,r,含义如上描述.接下来一行有

  5. debian终端菱形乱码修复

    最简安装debian的时候由于没有中文字库,若选择看中文环境会出现菱形乱码.先把zh.utf8换为us.utf8看着好顺眼些.按空格键取消已选的zh.utf8选项按空格键选择us.utf8选项ok

  6. 自定义可判断选项是否正确listbox

    截图如下:        1.实现Converter  获取到listbox,并得到listitem在listbox中的index public class ItemContainerToZIndex ...

  7. Virtualizing WrapPanel VS toolkit:WrapPanel

    用toolkit:WrapPanel的时候,LIST太大,内存不行,等下我试试 Virtualizing WrapPanel这个 http://www.codeproject.com/Articles ...

  8. Android BroadcasetReceiver

    ci@clinux:~/mp_mtk$ adb -s QGAEFYAAOFN7PNOB logcat PhoneReceiver:e *:S --------- beginning of system ...

  9. 从一个URL下载原始数据,基于byte字节,得到byte数组

    public static byte[] loadRawDataFromURL(String u) throws Exception { URL url = new URL(u); HttpURLCo ...

  10. sqlserver中distinct的用法(不重复的记录)

    下面先来看看例子: table表 字段1     字段2   id        name   1           a   2           b   3           c   4    ...