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. java使用sigar 遇到问题的解决方案

    先给大家介绍一个开源工具Sigar 官网:http://sigar.hyperic.com/ API:http://www.hyperic.com/support/docs/sigar/index-a ...

  2. H.264的一些资料整理

    本文转载自 http://blog.csdn.net/ljzcom/article/details/7258978, 如有需要,请移步查看. Technorati 标签: H.264 资料整理 --- ...

  3. 最小化安装Centos7后的部署(个人)

    一.配置网络 1.  自动获取IP地址 使用ip addr查看网络设备名称,我的网卡名称为enp0s3.找到设备名称后配置enp0s3的配置文件. 打开Vi /etc/sysconfig/networ ...

  4. MongoDB的分组统计 group

    mongodb中的分组聚合用$group,而且处理的最大数据量为100M如果超出需要写入到磁盘,使用格式如下: { $group: { _id: <expression>, <fie ...

  5. MongoDB与php的配合使用 【windows版】

    通过学习了如何使用和部署MongoDB,尝试了一下如何将mongodb应用到php的程式中去. 1.预备工作 首先得准备好mongodb,并按照相关方法部署以及服务能正常运行中. 对于初学者,可以参考 ...

  6. Yii2框架数据库增删改查小结

    User::find()->all();    //返回所有用户数据:User::findOne($id);   //返回 主键 id=1  的一条数据: User::find()->wh ...

  7. js读取json数据(php传值给js)

    <?php $array =array('fds','fdsa','fdsafasd');  // json_encode($array); ?> <html> <hea ...

  8. CSS练习

    看到一个CSS参考手册:http://css.doyoe.com/ 感谢感谢!

  9. c#中的结构与枚举

    结构 与c++不同的是,结构应该定义在命名空间或者类里面,成员变量叫字段,字段并且有访问控制符,每个字段前要加一个下划线 例子 using System; using System.Collectio ...

  10. 自己实现的库函数1(strlen,strcpy,strcmp,strcat)

    为了便于理解和使用库函数,先把自己实现的几个函数以及测试函数呈现如下. //求字符串长度的函数int my_strlen(const char* pStr){ assert(pStr != NULL) ...