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 ...
随机推荐
- C++将类的构造函数、析构函数声明为private或者protected的用途
如果将构造函数.析构函数声明为private或者protected,表示不能从类的外部正常调用构造和析构函数了. 这种用法的通常使用的场景如下: 1.如果不想让外面的用户直接构造一个类A的对象,而希望 ...
- Difference between ref and out parameters
Original link: http://www.dotnet-tricks.com/Tutorial/csharp/K0Hb060414-Difference-between-ref-and-ou ...
- iOS ARC下循环引用的问题 -举例说明strong和weak的区别
strong:适用于OC对象,作用和非ARC中的retain作用相同,它修饰的成员变量为强指针类型weak:适用于OC对象,作用和非ARC中的assign作用相同,修饰的成员变量为弱指针类型assig ...
- windows phone 8 开发系列(三)程序清单说明与配置
一 清单文件内容介绍 当我们先建了一个项目之后,我们可以看到vs自动会为我们创建了很多文件,正常人都会先一个个去翻看下每个文件都是干啥的,都主要写了些啥,在这些文件中,在Properies目录下面,我 ...
- 常用JS加密编码算法
//#region UTF8编码函数 function URLEncode(Str) { if (Str == null || Str == "") return "&q ...
- Linux上iptables防火墙的基本应用
1.安装iptables防火墙 yum install iptables -y 2. 清除已有的iptables规则 iptables -F iptables -X iptables -Z 3.显示i ...
- WinForm TreeView节点重绘,失去焦点的高亮显示
当用户焦点离开TreeView时,TreeView选中节点仍然高亮,但是颜色符合主题. 设置TreeView.HideSelection = False;可让选中节点保持高亮. 添加重绘事件 Tree ...
- mongodb 入门笔记
选择Mongo的关键是:这是一个 JSON 文档数据库. 1. Mongo 的术语 文档:一条完整的数据就是一个文档(对应于 MySQL 的一行). 集合:一组文档构成一个集合.类似 MySQL 中表 ...
- Translation001——android
请尊重原创,转载请注明出处: Author:KillerLegend Link:http://www.cnblogs.com/killerlegend/ BEGIN****************** ...
- 【转载】Powershell设置世纪互联Office365嵌套组发送权限
Start-Transcript ".\Set-GroupSendPermisionLog.txt" -Force function Get-DLMemberRecurse { $ ...