Post Order traverse binary tree using non-recursive way
Process analysis

- Stack = 5,
- Push 3, Stack = 5, 3. Pre = 5
- Current = 3, Pre = 5, Push 2 to the stack, stack = 5, 3, 2, Pre = 3
- Current = 2, Pre = 3, pop 2, PRINT 2, Stack = 5, 3. Pre = 2
- Current = 3, push 4, Stack = 5, 3 , 4. Pre = 3
- Current = 4, 4 is leaf node, pop 4. PRINT 4, Pre = 4, Stack = 5, 3
- Current = 3, Pre = 4, 4 is right child of 3, it means it goes up from right side, all visited. Pop one more element from stack, PRINT 3. Pre = 3. Stack = 5
- Current = 5, Pre = 3, 5 has right child, push 7, Stack = 5, 7, Pre = 5
- Current 7, which is right child of 5, meaning it's first time to visit 7, 7 has left child, push 6 to the stack. Stack = 5, 7, 6 Pre = 7
- Current = 6, 6 is 7's left child, but 6 is leaf node, pop 6. Print 6, Pre = 6. Stack = 5, 7
- Current = 7, 7 has right child? yes, 8. Push 8 to the stack, Stack = 5,7,8. Pre = 7
- Current = 8, 8 has no left child, has right child 10, push 10 to the stack. Stack = 5, 7, 8, 10. Pre = 8
- Current = 10, 10 is leaf node, pop 10, Print 10, Stack = 5,7,8, Pre = 10
- Current = 8, pop 8, Print 8, Stack = 5, 7, Pre = 8
- Current = 7, pop 7, Print 7, Stack = 5, Pre = 7
- Current = 5, pop 5, Print 5, stack = empty
public void PostOrderNonRecursion1StackV1()
{
Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>(); if (root == null)
{
return;
} TreeNode<T> current = this.root;
TreeNode<T> pre = null; stack.Push(this.root); while (stack.Count != )
{
current = stack.Peek(); // top down
if (pre == null || pre.leftChild == current || pre.rightChild == current)
{
if (current.leftChild != null)
{
stack.Push(current.leftChild);
}
else if (current.rightChild != null)
{
stack.Push(current.rightChild);
}
else
{
// leaf node, have to pop
Console.WriteLine("visit node {0}", stack.Pop().data);
}
}
// move up case from left node
else if (current.leftChild == pre)
{
if (current.rightChild != null)
{
stack.Push(current.rightChild);
}
else
{
Console.WriteLine("visit node {0}", stack.Pop().data);
}
}
// move up from right , which means all done, need pop up next one to figure out next action
else if (current.rightChild == pre)
{
Console.WriteLine("visit node {0}", stack.Pop().data);
} // remember the previous node, not parent node
pre = current;
}
}
The solution above uses one stack. If you use two stacks, there are the following two ways.
Solution 1 - do pre-order non-recursive firstly, but the sequence is root, right, left, not root, left and right.
Then store the result in stack 2, print stack 2, you will get the final result. Put code as below.
public void PostOrderNonRecursion2StacksV1()
{
Stack<TreeNode<T>> stack1 = new Stack<TreeNode<T>>();
Stack<TreeNode<T>> stack2 = new Stack<TreeNode<T>>(); TreeNode<T> current = root; if (current == null)
{
return;
} while (current != null)
{
stack2.Push(current);
Console.WriteLine(current.data);
stack1.Push(current);
current = current.rightChild;
} while (stack1.Count != )
{
current = stack1.Pop(); if (current.leftChild != null)
{
current = current.leftChild;
while (current != null)
{
stack2.Push(current);
stack1.Push(current);
current = current.rightChild;
}
}
} while (stack2.Count != )
{
Console.WriteLine("value = {0}", stack2.Pop().data);
}
}
Solution 2:
这个方法对于初学者很难想到,根节点先入栈,然后根节点出栈,存入栈2. 根节点的左孩子入栈,根节点的右孩子入栈。
然后右孩子出栈,入栈2. 右孩子的左右节点入栈1。这样栈2的元素实际从底往上是主根,右孩子,递归右左。 反过来就是先左后右, 再根节点。 下面是代码
public void PostOrderNonRecursion2StackV2()
{
Stack<TreeNode<T>> stack1 = new Stack<TreeNode<T>>();
Stack<TreeNode<T>> stack2 = new Stack<TreeNode<T>>(); TreeNode<T> current = root;
if (current == null)
{
return;
} stack1.Push(current); while (stack1.Count != )
{
current = stack1.Pop();
if (current.leftChild != null)
{
stack1.Push(current.leftChild);
} if (current.rightChild != null)
{
stack1.Push(current.rightChild);
} stack2.Push(current);
} while (stack2.Count != )
{
Console.WriteLine("value = {0}", stack2.Pop().data);
}
}
Post Order traverse binary tree using non-recursive way的更多相关文章
- Binary Tree Level Order Traversal,Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal Total Accepted: 79463 Total Submissions: 259292 Difficulty: Easy G ...
- 37. Binary Tree Zigzag Level Order Traversal && Binary Tree Inorder Traversal
Binary Tree Zigzag Level Order Traversal Given a binary tree, return the zigzag level order traversa ...
- CSharp Algorithm - How to traverse binary tree by breadth (Part II)
/* Author: Jiangong SUN */ Here I will introduce the breadth first traversal of binary tree. The pri ...
- 35. Binary Tree Level Order Traversal && Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal OJ: https://oj.leetcode.com/problems/binary-tree-level-order-trave ...
- LeetCode: Binary Tree Level Order Traversal && Binary Tree Zigzag Level Order Traversal
Title: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ...
- LeetCode之“树”:Binary Tree Level Order Traversal && Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal 题目链接 题目要求: Given a binary tree, return the level order traversal o ...
- 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 ...
- Morris InOrder Traverse Binary Tree 无需使用递归和栈
今天在切leetcode的时候看到一个Morris算法,用来中序遍历二叉树,非递归,O(1)空间.觉得很强大.记录一下. 基本思想是利用了Threaded Binary Tree. 步骤如下: cur ...
- programming review (c++): (2)binary tree, BFS, DFS, recursive, non-recursive
1.二叉树定义 // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *r ...
随机推荐
- Docker Swarm 高可用详解
Docker Swarm 高可用详解 Manager管理节点宕机后其他管理节点仍然可以使用管理 intermal distributed state store:内部分布式状态存储同步共享到每个节点. ...
- oracle flashback data archive闪回数据归档天坑之XID重用导致闪回查询数据重复
我们有个系统使用了Oracle flashback data archive闪回数据归档特性来作为基于时间点的恢复机制,在频繁插入.更新期间发现SYS_FBA_HIST_NNNN表中的XID被两个事务 ...
- 自制操作系统Antz(6)——内核初步,引入c语言
Antz系统更新地址: https://www.cnblogs.com/LexMoon/category/1262287.html Linux内核源码分析地址:https://www.cnblogs. ...
- nmon监控数据分析
性能测试中,各个服务器资源占用统计分析是一个很重要的组成部分,通常我们使用nmon这个工具来进行监控以及监控结果输出. 一. 在监控阶段使用类似下面的命令 ./nmon -f write_3s_20v ...
- HDU 5405 Sometimes Naive(动态树)
题意 \(n\) 个节点的树,每个点有点权,\(m\) 次操作,操作分两种,修改一个节点的点权,对于一个 \((u,v)\) ,询问 \(\displaystyle\sum_{i=1}^n\sum_{ ...
- .NET Core 配置GC工作模式与内存的影响
.NET Core 配置GC工作模式与内存的影响 .NET Core GC 原文:https://blog.markvincze.com/troubleshooting-high-memory-usa ...
- 8、zabbix监控方式及分布式监控(04)
zabbix支持的监控方式 zabbix所能够显示的且可指定为监控接口类型的监控方式: Agent passive active SNMP:Simple Network Management Prot ...
- 解决依赖冲突:maven-enforcer-plugin插件
我们会经常碰到这样的问题,在pom中引入了一个jar,里面默认依赖了其他的jar包.jar包一多的时候,我们很难确认哪些jar是我们需要的,哪些jar是冲突的.此时会出现很多莫名其妙的问题,什么类找不 ...
- js 字符串跟数组的相互转化
一:字符串转化为数组 例子: var str = "3:2;2:1"; 要变成 arr= [{ a:"3", b:"2", bol:fals ...
- 亲自打造Deferred对象
经过对比之后,决心学习jQuery,自己打造一个Deferred对象.var util = require('./util.js');function Callbacks() { var list = ...