二叉树的后序遍历BTPostorderTraversal
来源:互联网 发布:体育场馆播放软件 编辑:程序博客网 时间:2024/05/29 00:31
/*
* 后序遍历二叉树
* 核心思想是用栈做辅助空间,先从根节点往左一直入栈,直到为空,然后判断栈顶元素的右孩子,
* 如果为空或被访问过,说明此时栈顶为要访问的节点,出栈然后访问即可;
* 否则从它开始重复左孩子入栈的过程,接下来再判断栈顶元素的右孩子...直到栈空。
*/
public class BTPostorderTraversal
{
static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
}
}
public static ArrayList<Integer> postorderTraversal(TreeNode root)
{
if(root == null)
{
return null;
}
ArrayList<Integer> _values = new ArrayList<Integer>();
Deque<TreeNode> _nodes = new ArrayDeque<TreeNode>();
TreeNode _pNode = root;
TreeNode _pre = null;//记录上一个访问的节点
while(_pNode != null || !_nodes.isEmpty())
{
while(_pNode != null)
{
_nodes.push(_pNode);
_pNode = _pNode.left;
}
_pNode = _nodes.peek();
//如果右节点为空或右节点被访问过,说明该节点就是要访问的节点
if(_pNode.right == null || _pNode.right == _pre)
{
_values.add(_nodes.pop().val);
_pre = _pNode;//记录被访问过的节点
_pNode = null;
}
else
{
_pNode = _pNode.right;
}
}
return _values;
}
}
* 后序遍历二叉树
* 核心思想是用栈做辅助空间,先从根节点往左一直入栈,直到为空,然后判断栈顶元素的右孩子,
* 如果为空或被访问过,说明此时栈顶为要访问的节点,出栈然后访问即可;
* 否则从它开始重复左孩子入栈的过程,接下来再判断栈顶元素的右孩子...直到栈空。
*/
public class BTPostorderTraversal
{
static class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
}
}
public static ArrayList<Integer> postorderTraversal(TreeNode root)
{
if(root == null)
{
return null;
}
ArrayList<Integer> _values = new ArrayList<Integer>();
Deque<TreeNode> _nodes = new ArrayDeque<TreeNode>();
TreeNode _pNode = root;
TreeNode _pre = null;//记录上一个访问的节点
while(_pNode != null || !_nodes.isEmpty())
{
while(_pNode != null)
{
_nodes.push(_pNode);
_pNode = _pNode.left;
}
_pNode = _nodes.peek();
//如果右节点为空或右节点被访问过,说明该节点就是要访问的节点
if(_pNode.right == null || _pNode.right == _pre)
{
_values.add(_nodes.pop().val);
_pre = _pNode;//记录被访问过的节点
_pNode = null;
}
else
{
_pNode = _pNode.right;
}
}
return _values;
}
}
阅读全文
0 0
- 二叉树的后序遍历BTPostorderTraversal
- 二叉树的后序遍历
- 二叉搜索树的后序遍历
- 二叉搜索树的后序遍历
- 二叉树的后序遍历
- 二叉搜索树的后序遍历
- 二叉树的后序遍历算法
- 题目:二叉树的后序遍历
- LintCode -- 二叉树的后序遍历
- Lintcode 二叉树的后序遍历
- 二叉搜索树的后序遍历
- LintCode:二叉树的后序遍历
- 二叉树的后序遍历
- 二叉查找树的后序遍历
- 二叉搜索树的后序遍历
- lintcode,二叉树的后序遍历
- 后序二叉线索树的遍历
- 【数据结构】二叉树的后序遍历
- DNS在什么时候使用TCP,在什么时候使用UDP
- HTML基础学习-7- 列表学习3
- ESP8266浏览器发送数据到远程设备测试OK
- Discovering Gold (概率dp(基础))
- POJ 1964 City Game 笔记
- 二叉树的后序遍历BTPostorderTraversal
- MySQL表空间碎片整理
- 学习淘淘商城第九十七课(商品详情页面对加入购物车进行改造)
- Solr(1.安装)
- 微信小程序随笔
- 自定义view画圆形进度条(进度为初始设置的值,不变化)
- python学习基础一:
- Git 分支
- ORACLE RAC ONE NODE技术介绍