java 二叉树遍历_二叉树遍历方式之java实现

本文介绍了二叉树的三种遍历方法——前序、中序和后序遍历,分别给出了递归和非递归的Java实现。通过递归方式,关键在于在正确的位置插入逻辑判断;非递归实现则利用栈来模拟递归过程。详细代码和思路助你理解二叉树遍历。
摘要由CSDN通过智能技术生成

前言

最近在准备实习,发现虽然做了挺多算法题,总感觉思维体系没有建立起来,遂准备在这里记录一下,先从树说起吧,这篇主要是二叉树的遍历,包括递归和非递归两种方式。

递归实现

其实关于二叉树的题全是套路,递归遍历如果是前序,就在最前边做逻辑判断;中序就在中间,后序就在最后,首先来搭个架子。

架子(前中后通吃架子)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值