144. Binary Tree Preorder Traversal
2016-04-09 14:17
381 查看
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
return
思路:普通递归的先序遍历就就不写了,下面给出一种非递归的先序遍历,用stack来实现
public static void preorder(List<Integer> list, TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
list.add(root.val);
stack.push(root);
root = root.left;
}
root=stack.pop();
root=root.right;
}
}
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,2,3].
思路:普通递归的先序遍历就就不写了,下面给出一种非递归的先序遍历,用stack来实现
public static void preorder(List<Integer> list, TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
list.add(root.val);
stack.push(root);
root = root.left;
}
root=stack.pop();
root=root.right;
}
}
相关文章推荐
- 瀑布流的实现原理
- 在线补丁的激活方法、装置及系统
- STL vector
- ScrollView嵌套ListView问题的四种解决方案
- POJ 2220 Sumsets(递推)
- 《JAVA开发环境的熟悉》实验报告——20145337
- 31.多线程 Thread类
- 关系型数据库中的范式问题?
- 深度学习概述
- java单例类(Singleton)
- 表格
- AndroidStudio部署项目时出现错误:Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled
- Linux内核分析:实验七--Linux内核如何装载和启动一个可执行程序
- 蓝桥杯第十题,
- SVN安装历程
- 一种Java异常传播的静态结构抽取方法
- ArcGIS之3D Analyst
- rails中引入god
- 组合框
- 设计模式-建造者模式