144. Binary Tree Preorder Traversal(Tree)
2016-07-18 00:17
357 查看
题目:
Given a binary
tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
return
二叉树的前遍历,三种解法:
递归:
栈:
采用栈模拟进行遍历,时间复杂度O(N),空间复杂度O(N):
Morris遍历法:
采用线索二叉树,将子节点右节点指向当前节点的前驱节点。时间复杂度O(N),空间复杂度O(1)
Given a binary
tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,2,3].
二叉树的前遍历,三种解法:
递归:
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new LinkedList<Integer>(); return help(root,result); } List<Integer> help(TreeNode root,List<Integer> result) { if(root != null) { result.add(root.val); result=help(root.left,result); result=help(root.right,result); } return result; }
栈:
采用栈模拟进行遍历,时间复杂度O(N),空间复杂度O(N):
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new LinkedList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root != null) stack.push(root); while(!stack.isEmpty()) { TreeNode temp = stack.pop(); result.add(temp.val); if(temp.right!=null)stack.push(temp.right); if(temp.left!=null)stack.push(temp.left); } return result; }
Morris遍历法:
采用线索二叉树,将子节点右节点指向当前节点的前驱节点。时间复杂度O(N),空间复杂度O(1)
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new LinkedList<Integer>(); TreeNode cur = root; while(cur != null) { if(cur.left == null) { result.add(cur.val); cur = cur.right; } else { //未线索化 TreeNode temp=cur.left; while(temp.right!=null && temp.right!=cur) { temp=temp.right; } if(temp.right==null) { result.add(cur.val); temp.right=cur; cur=cur.left; } else { //线索化,清理线索 temp.right=null; cur=cur.right; } } } return result; }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树