CODE 142: Binary Tree Postorder Traversal
2013-11-25 22:37
393 查看
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
public ArrayList<Integer> postorderTraversal(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (null == root) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (!stack.isEmpty() || null != root) {
if (null != root) {
stack.push(root);
root = root.left;
} else {
root = stack.peek();
if (null != root.right) {
TreeNode right = root.right;
stack.peek().left = null;
stack.peek().right = null;
stack.push(right);
root = right.left;
} else {
stack.pop();
result.add(root.val);
root = null;
}
}
}
return result;
}
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[3,2,1].
public ArrayList<Integer> postorderTraversal(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (null == root) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (!stack.isEmpty() || null != root) {
if (null != root) {
stack.push(root);
root = root.left;
} else {
root = stack.peek();
if (null != root.right) {
TreeNode right = root.right;
stack.peek().left = null;
stack.peek().right = null;
stack.push(right);
root = right.left;
} else {
stack.pop();
result.add(root.val);
root = null;
}
}
}
return result;
}
相关文章推荐
- linux 系统监控分析工具
- 丢失的游戏
- 有关Yii的main.php 主配置文件的说明
- cygwin下的第一次编程记录
- RMAN命令总结
- IOS 检测摇晃 几个问题
- 5.6 PREDICTING PROBABILITIES
- hdu1864最大报销额 (01背包)
- PHP自定义函数使用外部变量
- IOS 检测摇晃 几个问题
- asp.net验证控件
- 腾讯 2012 实习生笔试题
- 【Oracle】Oracle异常简介
- MongoDB实战(11)Sharding 分片(下)
- MongoDB实战(11)Sharding 分片(下)
- String、StringBuffer、StringBuilder
- HDU1217:Arbitrage(SPFA)
- 获取Android控件的宽和高
- SVN小小用法(一)svn服务器搭建
- 让线程支持超时