Binary Search Tree In-Order Traversal Iterative Solution
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:
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;
}
}
}
|
A 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:
- 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.
- 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的更多相关文章
- [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 ...
- [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 ...
- LeetCode 1008. Construct Binary Search Tree from Preorder Traversal
原题链接在这里:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/ 题目: Retu ...
- 【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 ...
- 【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 ...
- 【LeetCode】1008. Construct Binary Search Tree from Preorder Traversal 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- leetcode@ [173] Binary Search Tree Iterator (InOrder traversal)
https://leetcode.com/problems/binary-search-tree-iterator/ Implement an iterator over a binary searc ...
- 算法与数据结构基础 - 二叉查找树(Binary Search Tree)
二叉查找树基础 二叉查找树(BST)满足这样的性质,或是一颗空树:或左子树节点值小于根节点值.右子树节点值大于根节点值,左右子树也分别满足这个性质. 利用这个性质,可以迭代(iterative)或递归 ...
- 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 ...
随机推荐
- hdu 六度分离 floyd
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1869 题意分析:比较简单的最短路算法,最后只需判断最远两点距离是否大于7即可. /*六度分离 Time ...
- android 数据库_sql语句总结
表的创建db.execSQL("create table info(_id integer primary key autoincrement,name varchar(20)") ...
- 13个SQL优化技巧
避免无计划的全表扫描<!--?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" ...
- net 中捕获摄像头视频的方式及对比(How to Capture Camera Video via .Net) (转)
作者:王先荣前言 随着Windows操作系统的不断演变,用于捕获视频的API接口也在进化,微软提供了VFW.DirectShow和MediaFoundation这 三代接口.其中VFW早已被Di ...
- scp实现mac与linux服务器之间文件传输
1.mac上传文件到linux服务器 scp 文件名 用户名@服务器ip:目标路径如:scp /Users/test/testFile test@xxx.xxx.xxx.xxx:/test/ 2.ma ...
- nginx配置:支持phpfastcgi,nginx和php-cgi通信,部分nginx常量解释
支持phpfastcgi的配置如下: server { listen 8000; server_name localhost; root F:/home/projects/test; i ...
- MySQL实战积累
IFNULL(expr1,expr2)的用法:假如expr1不为NULL,则IFNULL()的返回值为 expr1; 否则其返回值为expr2. 索引:http://www.cnblogs.com ...
- mysql基础三(视图、触发器、函数、存储过程、事务、防注入)
一.视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,并可以将其当作表来使用. 1.创建视图 -格式:CREATE ...
- 虚拟机开机提示:This virtual machine appears to be in use
[原因]:由于电脑非正常关机导致,重新启动虚拟机就会出现This virtual machine appears to be in use的提示.[解决方法]:到虚拟机的安装目录下删除所有.lck的目 ...
- 11G RAC 简单命令
1.查看集群状态: [root@rac1 ~]# su - grid [grid@rac1 ~]$ crsctl check clusterCRS-4537: Cluster Ready Servic ...