这是一道将二叉树先序遍历,题目不难。

首先采用深搜递归

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static List<Integer> resultlist = new ArrayList<Integer>(); public static void dfs (TreeNode root ,boolean flag ) {
if(flag==true)
{
resultlist.clear();
}
if(root==null)
{
return ;
} resultlist.add(root.val); if(root.left!=null)
{
dfs(root.left,false);
}
if(root.right!=null)
{
dfs(root.right,false);
} } public static List<Integer> preorderTraversal(TreeNode root ) {
dfs(root,true);
return resultlist;
} }

非递归实现方式

 public static List<Integer> preorderTraversal(TreeNode root ) {
List<Integer> result = new ArrayList<>(); if(root == null)
return result; Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root); while(!stack.empty()){
TreeNode n = stack.pop();
result.add(n.val); if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
} }
return result;
}

最新文章

  1. PHP 对象 “==” 与 “===”
  2. winows下使用ssh服务远程登录vbox中的虚拟机
  3. Silverlight C1.Silverlight.FlexGrid 表格动态列
  4. C#关键字
  5. ajax连接池和XMLHttpRequest
  6. hadoop运行流程分析源代码级
  7. 需要我们了解的SQL Server阻塞原因与解决方法
  8. 简单的socket方法
  9. scala学习笔记1(表达式)
  10. Smobiler 4.4已正式发布!(Smobiler能让你在Visual Studio上开发APP)
  11. 【前端基础系列】理解bind方法使用与实现
  12. [Aaronyang] 写给自己的WPF4.5 笔记9[复杂数据处理三步曲,数据展示ListView泪奔2/3]
  13. idea导入eclipse中的maven项目
  14. DBGrid添加行号编写笔记
  15. python中logging日志基本用法,和进程安全问题
  16. 使用wsgiref库diy简单web架构
  17. 阿里云ECS购买优惠码
  18. 简单整理React的Context API
  19. HDU1950-Bridging signals-最长上升子序列
  20. django 自定义过滤器中的坑.

热门文章

  1. ng2父子模块通信@ViewChild和@Inject
  2. 微软开业网站----精华 http://www.microsoft.com/opensource/directory.aspx
  3. [xdoj1227]Godv的数列(crt+lucas)
  4. 日期组件wdatepicker
  5. VMWare虚拟机Bridged类型网卡ping不通的原因和解决办法
  6. 获得用户IP、城市、国家等信息的api接口
  7. ssm重新开发计科院新闻网站
  8. ue4 c++ anim notify
  9. 2014-10-24 NOIP欢乐赛
  10. 洛谷P2513 [HAOI2009]逆序对数列