Java实现二叉树的四大遍历(递归+非递归)

二叉树前,中,后序遍历(递归实现):

public class Tree{
	//构建二叉树
	class TreeNode{
		int val=0;
		TreeNode left=null;
		TreeNode right=null;
		public TreeNode(int val){
			this.val=val;
		}
	}
	//前序遍历(递归)
	public void prevOrder(TreeNode root){
		if(root==null) return;
		System.out.print(root.val+" ");
		prevOrder(root.left);
		prevOrder(root.right);
	}
	//中序遍历(递归)
	public void inOrder(TreeNode root){
		if(root==null) return ;
		inOrder(root.left);
		System.out.print(root.val+" ");
		inOrder(root.right);
	}
	//后序遍历(递归)
	public void postOrder(TreeNode root){
		if(root==null) return ;
		postOrder(root.left);
		postOrder(root.right);
		System.out.print(root.val+" ");
	}
}

前,中,后序遍历(非递归实现)+层次遍历:

public class Tree{
	//构建二叉树
	class TreeNode{
		int val=0;
		TreeNode left=null;
		TreeNode right=null;
		public TreeNode(int val){
			this.val=val;
		}
	}
	//前序遍历(非递归)
	public List<Integer> preOrder(TreeNode root){
		List<Integer> list=new LinkedList<>();
		Stack<TreeNode> stack=new Stack<>();
		if(root==null) return list;
		stack.push(root);
		while(!stack.isEmpty()){
			TreeNode node=stack.pop();
			list.add(node.val);
			if(node.right!=null){
				stack.push(node.right);
			}
			if(node.left!=null){
				stack.push(node.left);
			}
		}
		return list;
	}
	//中序遍历(非递归)
	public List<Integer> inOrder(TreeNode root){
		List<Integer> list=new LinkedList<>();
		Stack<TreeNode> stack=new Stack<>();
		TreeNode cur=root;
		while(cur!=null || !stack.isEmpty()){
			while(cur!=null){
				stack.push(cur);
				cur=cur.left;
			}
			cur=stack.pop();
			list.add(cur.val);
			cur=cur.right;
		}
		return list;
	}
	//后序遍历(非递归)
	public List<Integer> postOrder(TreeNode root){
		LinkedList<Integer> list=new LinkedList<>();
		LinkedList<TreeNode> stack=new LinkedList<>();
		if(root==null) return list;
		stack.push(root);
		while(!stack.isEmpty()){
			TreeNode node=stack.pop();
			list.addFirst(node.val);
			if(root.left!=null){
				stack.add(root.left);
			}
			if(root.right!=null){
				stack.add(root.right);
			}
		}
		return list;
	}
	//层次遍历
	public LinkedList<LinkedList<Integer>> print(TreeNode root){
		LinkedList<LinkedList<Integer>> list=new Linkedlist<>();
		LinkedList<TreeNode> queue=new LinkedList<>();
		if(root==null) return list;
		queue.add(root);
		while(queue.size()!=0){
			int count=queue.size();
			LinkedList<Integer> list1=new LinkedList<>();
			while(count>0){
				TreeNode node=queue.remove(0);
				list1.add(node.val);
				if(root.left!=null){
					queue.add(root.left);
				}
				if(root.right!=null){
					queue.add(root.right);
				}
				count--;
			}
			list.add(list1);
		}
		return list;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值