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 ...
随机推荐
- DataFrame数据转为list,再逐行写入Excel
首先使用np.array()函数把DataFrame转化为np.ndarray(), 再利用tolist()函数把np.ndarray()转为list, 示例代码如下: # -*- coding:ut ...
- Bumped!【最短路】(神坑
问题 B: Bumped! 时间限制: 1 Sec 内存限制: 128 MB 提交: 351 解决: 44 [提交] [状态] [命题人:admin] 题目描述 Peter returned fr ...
- Postman接口调试神器
Postman起初源自googleBrowser的一款插件,现已经有单独软件,当然之前的插件也存在 它主要是用于接口的的调试 接口请求的流程 一.GET请求 GET请求:点击Params,输入参数及 ...
- C++ 将 std::string 转换为 char*
参考: std::string to char* C++ 将 std::string 转换为 char* 目前没有直接进行转换的方法.必须通过string对象的c_str()方法,获取C-style的 ...
- Springboot解决war包放到Tomcat服务器上404的特殊情况
Springboot解决war包放到Tomcat服务器上404的特殊情况 原文链接:https://www.cnblogs.com/blog5277/p/9330577.html 原文作者:博客园-- ...
- POJ 1088 滑雪(模板题 DFS+记忆化)
Description Michael喜欢滑雪百这并不奇怪, 因为滑雪的确很刺激.可是为了获得速度,滑的区域必须向下倾斜,而且当你滑到坡底,你不得不再次走上坡或者等待升降机来载你.Michael想知道 ...
- 基于C语言的磁引导园丁机器人源程序 --单片机应用
GardenRobot.c: #include"reg52.h" #include"intrins.h" #define uchar unsigned char ...
- 【异常】idea执行Main方法出现 Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest
一.异常复现步骤 1)首先得是一个Spring MVC项目 注:Spring Boot项目有内置的web 容器,不会出现该问题 2)main方法存在于使用HttpServletRequest类的类中 ...
- Linux出现wrong ELF class: ELFCLASS64
安装软件时出现问题 ×.so.×:wrong ELF class: ELFCLASS64 ,大致的意思是软件是32位的,需要32位的 ×.so.×动态链接库,而系统是64位的所提供的该 动态链接库 ...
- Python进程、线程、协成
什么是线程?程序执行的最小单位线程是进程中的一个实体,是被系统独立调度和分派的基本单位 线程的创建threading.Thread(target = 变量名) 线程的资源竞争问题线程是可以资源共享的同 ...