leetcode 144. Binary Tree Preorder Traversal
2016-05-25 13:38
281 查看
原文链接http://www.myexception.cn/program/1958647.html
For example:
Given binary tree {1,#,2,3},
![](http://img.blog.csdn.net/20160525133654956)
return [1,2,3].
题目
Given a binary tree, return the preorder traversal of its nodes’ values.For example:
Given binary tree {1,#,2,3},
return [1,2,3].
解1(递归)
//前序遍历 递归 public static void preorderTraversal(TreeNode root){ if(root==null) return ; System.out.print(root.val+" "); inorderTraversal(root.left); inorderTraversal(root.right); }
解2(非递归方法)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); Stack<TreeNode> nodeStack=new Stack<>(); while(true) { while(root!=null) { res.add(root.val); nodeStack.push(root); root=root.left; } if(nodeStack.isEmpty()) break; TreeNode tempNode=nodeStack.pop(); root=tempNode.right; } return res; } }
解3(非递归)
//前序遍历 非递归 public static List<TreeNode> preorderTraversal2(TreeNode root){ List<TreeNode> tList=new ArrayList<TreeNode>(); Stack<TreeNode> tStack=new Stack<TreeNode>(); tStack.push(root); while(!tStack.isEmpty()){ TreeNode p=tStack.pop(); tList.add(p); System.out.print(p.val+" "); if(p.right!=null) tStack.push(p.right); if(p.left!=null) tStack.push(p.left); } return tList; }
相关文章推荐
- 《构建之法》阅读笔记09-用户体验
- android intent.setType("type");的含义
- python数据分析6:双色球 使用线性回归算法预测下期中奖结果
- 【未解决 存疑】jsp中乱码问题,修改mysql5.6 character_set_results
- Duplicate column name 'xxx'错误
- wiki百科翻译之Lean software development之Deliver as fast as possible
- AngularJs学习笔记(一)初认识AngularJs
- [leetcode] 【数组】48. Rotate Image
- 条件注释判断浏览器版本<!--[if lt IE 9]>
- OpenStack搭建,安装Dashboard异常
- POJ2418 二叉排序树 && 字典树写法
- JAVA线程池的分析和使用
- opencv交叉编译第二版
- LINUX常用网络测试命令
- sikuli自动化测试html报告输出
- SQLite for xamarin
- mongodb分布式查询
- iOS开发中对于第三方AFNetworking的使用
- pjax实现无刷新
- 图片转化成base64字符串 && base64字符串转化成图片