二叉树的前中后序遍历用递归做很简单,然而非递归版本有些难度,面试常考其非递归版本,主要用到双端队列。
前序遍历
- 非递归版本
public class solution {
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
if(root==null) return res;
queue.push(root);
while(!queue.isEmpty()){
root = queue.pop();
res.add(root.val);
if(root.right!=null) queue.push(root.right);
if(root.left!=null) queue.push(root.left);
}
return res;
}
}
后序遍历
- 非递归版本
后序遍历的一个取巧方法就是把前序遍历倒着打印一遍,考虑到是双端队列,这样做很容易。
public class solution {
public List<Integer> postorderTraversal(TreeNode root){
LinkedList<Integer> res = new LinkedList<>();
Deque<TreeNode> queue = new LinkedList<>();
if(root==null) return res;
queue.push(root);
while(!queue.isEmpty()){
root = queue.removeFirst();
res.addFirst(root.val);
if(root.left!=null) queue.push(root.left);
if(root.right!=null) queue.push(root.right);
}
return res;
}
}
中序遍历
- 非递归版本
需要先一直遍历到最左节点,再依次返回遍历右节点。
public class solution {
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> res = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
while(root!=null||!queue.isEmpty()){
while(root!=null){
queue.push(root);
root=root.left;
}
root = queue.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
层序遍历
层序遍历的递归版本也比较难想,主要用到DFS;非递归版本用到BFS,还是考虑双端队列来实现。
- 非递归版本
public class solution{
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
if(root==null) return res;
queue.push(root);
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<>();
int size = queue.size();
while(size-->0){
root = queue.removeLast();
list.add(root.val);
if(root.left!=null) queue.push(root.left);
if(root.right!=null) queue.push(root.right);
}
res.add(list);
}
return res;
}
}
- 递归版本
public class solution{
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
int level = 0;
DFS(res,level,root);
return res;
}
public void DFS(List<List<Integer>> res, int level, TreeNode root){
if(root==null) return;
if(level>=res.size()) res.add(new ArrayList<Integer>());
res.get(level).add(root.val);
DFS(res,level+1,root.left);
DFS(res,level+1,root.right);
}
}