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. 【leetcode】367. Valid Perfect Square

    题目描述: Given a positive integer num, write a function which returns True if num is a perfect square e ...

  2. Lucene使用IKAnalyzer分词实例 及 IKAnalyzer扩展词库

    文章转载自:http://www.cnblogs.com/dennisit/archive/2013/04/07/3005847.html 方案一: 基于配置的词典扩充 项目结构图如下: IK分词器还 ...

  3. Java中的集合类

    实线边框的是实现类,比如ArrayList,LinkedList,HashMap等 折线边框的是抽象类,比如AbstractCollection,AbstractList,AbstractMap等, ...

  4. DataGridview动态添加列

    1.获取数据源(select * from table名称) 2.动态绑定数据源 private void GetTableInfo(DataTable dt) { listBh = new List ...

  5. javascript 创建对象及对象原型链属性介绍

    我们知道javascript里定义一个普通对象的方法,如: let obj = {}; obj.num = 1; obj.string = 'string'; obj.func = function( ...

  6. 为什么24位位图(真彩色)的biSizeImage不等于(biWidth*biBitCount+31)/32*4*biHeight?

    规定的,规定BMP文件的像素数据是按行存储的,而且每行的字节数必须为4的倍数,如果实际的像素数据不是4的倍数咋办?这就需要字节对齐,对齐是在一行的末尾添0以补足一行的字节数为4的倍数, ( biWid ...

  7. SQL中的自定义函数Function

    先给出一个链接吧,别人写的:http://www.cnblogs.com/diony/archive/2010/12/17/1909014.html 总结得很全面,感谢感谢!自己练习了一下后面的例子, ...

  8. Python LOGGING使用方法

    Python LOGGING使用方法 1. 简介 使用场景 场景 适合使用的方法 在终端输出程序或脚本的使用方法 print 报告一个事件的发生(例如状态的修改) logging.info()或log ...

  9. 通过数据绑定模板得到对应的Item控件

    这类控件都继承于Selector,其中主要有ComboBox.listview.listbox.datagrid. 由于个人对WPF的了解所有可能有遗漏,希望各位能够指出一起进步. 在遍历上面控件时主 ...

  10. 1014. Waiting in Line (30)

    Suppose a bank has N windows open for service. There is a yellow line in front of the windows which ...