lintcode--二叉树的前序遍历
来源:互联网 发布:Linux sl rl 休眠 编辑:程序博客网 时间:2024/05/21 07:09
给出一棵二叉树,返回其节点值的前序遍历。
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* 维护一个栈,将根节点入栈,然后只要栈不为空,出栈并访问,接着依次将访问节点的右节点、左节点入栈。
* 这种方式应该是对先序遍历的一种特殊实现(看上去简单明了),但是不具备很好的扩展性,在中序和后序方式中不适用
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root){
Stack<TreeNode> stack = new Stack<TreeNode>();
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
//先保存根结点
stack.push(root);
while(!stack.empty()){
TreeNode head = stack.pop();
list.add(head.val);
//先右进栈
if(head.right != null){
stack.push(head.right);
}
//再左进栈
if(head.left != null){
stack.push(head.left);
}
}
return list;
}
}
- LintCode -- 二叉树的前序遍历
- lintcode 二叉树的前序遍历
- lintcode,二叉树的前序遍历
- LintCode-二叉树的前序遍历
- lintcode 二叉树的前序遍历
- LintCode 二叉树的前序遍历
- lintcode二叉树的前序遍历
- 二叉树的前序遍历-LintCode
- Lintcode 二叉树的前序遍历
- lintcode--二叉树的前序遍历
- lintcode:二叉树的前序遍历
- lintcode-二叉树的前序遍历(非递归)-66
- LintCode之二叉树的前序遍历
- Lintcode 66 二叉树的前序遍历
- LintCode | 66. 二叉树的前序遍历
- lintcode——二叉树的前序遍历
- lintcode 66 二叉树的前序遍历
- LintCode 66 二叉树的前序遍历
- Android Studio获取开发版和发布版的MD5和SHA1
- Java多线程(八)之Semaphore、CountDownLatch、CyclicBarrier、Exchanger
- 0817 T2 钟
- SG详解
- 网络中出现TCP、UDP粘包、分包的两点解决办法
- lintcode--二叉树的前序遍历
- Linux快速体验
- 缓存算法, cache
- 编写Vim脚本
- IDEA中使用GIT
- 个位数统计
- Kafka 0.10 新特性介绍
- log4j多路径输出问题
- java Pattern和Matcher详解