前言
最近在准备实习,发现虽然做了挺多算法题,总感觉思维体系没有建立起来,遂准备在这里记录一下,先从树说起吧,这篇主要是二叉树的遍历,包括递归和非递归两种方式。
递归实现
其实关于二叉树的题全是套路,递归遍历如果是前序,就在最前边做逻辑判断;中序就在中间,后序就在最后,首先来搭个架子。
架子(前中后通吃架子)
public List mlr(TreeNode root){
List res=new ArrayList<>();
helper(res,root);
return res;
}
前序遍历
public void helper(List res,TreeNode root){
if(root==null) return;
res.add(root.val);
helper(res,root.left);
helper(res,root.right);
}
中序遍历
public void helper(List res,TreeNode root){
if(root==null) return;
helper(res,root.left);
res.add(root.val);
helper(res,root.right);
}
后序遍历
public void helper(List res,TreeNode root){
if(root==null) return;
helper(res,root.left);
helper(res,root.right);
res.add(root.val);
}
非递归实现
非递归其实思路就是用栈来模拟递归的过程。
前序遍历
public List mlr(TreeNode root){
Stack stack=new Stack<>();
List res=new ArrayList<>();
if(root==null) return res;
stack.push(root);
while(!stack.isEmpty()){
root=stack.pop();
res.add(root.val);
if(root.right!=null) stack.push(root.right);
if(root.left!=null) stack.push(root.left);
}
return res;
}
中序遍历
public List lmr(TreeNode root){
Stack stack=new Stack<>();
List res=new ArrayList<>();
if(root==null) return res;
while(root!=null || !stack.isEmpty()){
if(root!=null){
stack.push(root);
root=root.left;
}
else{
root=stack.pop();
res.add(root.val);
root=root.right;
}
}
return res;
}
后序遍历
public List lmr(TreeNode root){
Stack stack=new Stack<>();
List res=new ArrayList<>();
if(root==null) return res;
stack.push(root);
while(!stack.isEmpty()){
root=stack.pop();
res.add(0,root.val);
if(root.left!=null) stack.push(root.left);
if(root.right!=null) stack.push(root.right);
}
return res;
}
其实前序和后序处理就是调换了下~
总结
这就是所谓的二叉树遍历了,希望下次面试前不要这么紧张了hhhhh