lintcode--二叉树的后序遍历
来源:互联网 发布:粉红色的火烈鸟 知乎 编辑:程序博客网 时间:2024/05/27 06:16
给出一棵二叉树,返回其节点值的后序遍历。
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [3,2,1]
//Recursive递归
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
result.addAll(postorderTraversal(root.left));
result.addAll(postorderTraversal(root.right));
result.add(root.val);
return result;
}
/*
后序遍历递归定义:先左子树,后右子树,再根节点。
后序遍历的难点在于:
需要判断上次访问的节点是位于左子树,还是右子树。
若是位于左子树,则需跳过根节点,先进入右子树,再回头访问根节点;
若是位于右子树,则直接访问根节点。
*/
//Iterative
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode prev = null; // 以前走过的节点
TreeNode curr = root;//当前访问的结点
if (root == null) return result;
stack.push(root);
while (!stack.empty()) {
curr = stack.peek();
//一个根节点被访问的前提是:无右子树或右子树已被访问过
if (prev == null || prev.left == curr || prev.right == curr) {
// 遍历树
if (curr.left != null) {
stack.push(curr.left);
} else if (curr.right != null) {
stack.push(curr.right);
}
} else if (curr.left == prev) { // 从左边穿过树
if (curr.right != null) {
stack.push(curr.right);
}
} else { // traverse up the tree from the right
result.add(curr.val);
stack.pop();
}
prev = curr;
}
return result;
}
- LintCode -- 二叉树的后序遍历
- Lintcode 二叉树的后序遍历
- LintCode:二叉树的后序遍历
- lintcode,二叉树的后序遍历
- LintCode-二叉树的后序遍历
- lintcode 二叉树的后序遍历
- LintCode 二叉树的后序遍历
- 二叉树的后序遍历-LintCode
- lintcode二叉树的后序遍历
- LintCode 二叉树的后序遍历
- lintcode--二叉树的后序遍历
- LintCode-剑指Offer-(68)二叉树的后序遍历
- Lintcode 68 二叉树的后序遍历
- LintCode | 68. 二叉树的后序遍历
- lintcode——二叉树的后序遍历
- lintcode 68 二叉树的后序遍历
- LintCode 67 二叉树的后序遍历
- [LintCode]68.二叉树的后序遍历
- 算法题目---包含min函数的栈
- Java自动装箱/拆箱
- Java学习day6
- Linq语法详细
- JAVA虚拟机系列(八)
- lintcode--二叉树的后序遍历
- linq join on 多条件
- java基础(三):移位符的运用
- 利用元素属性值进行排序的简单实例
- springmvc从数据库中读取数据并且显示成选择框工具类
- 详解MyBatis的动态SQL
- Android本地缓存图片示例代码
- Jedis的连接和使用
- Java学习day7