二叉树的各种遍历方式

class TreeNode{
	TreeNode root;
	TreeNode left;
	TreeNode right;
	int val;
}
public class TreeNodeGo{
	//深度优先搜索(先序、中序、后序)
	public void DFS(TreeNode root){
		if(root==null) return;
		if(root.left!=null) DFS(root.left);
		if(root.right!=null) DFS(root.right);
		System.out.println(root.val);
	}
	//广度优先搜索(按层遍历)
	public void BFS(TreeNode root){
		Queue<TreeNode> queue=new LinkedList<>();
		if(root!=null){
			queue.add(root);
			whlie(!queue.isEmpty()){
				TreeNode node=queue.poll();//移除并返回队列首的元素
				System.out.println(node.val):
				if(node.left!=null)queue.add(node.left);
				if(node.right!=null)queue.add(node.right);
			}
		}
	}
	//先序遍历(递归)
	public void PrePrintTreeNode(TreeNode root){
		if(root!=null){
			System.out.Println(root.val);
			PrePrintTreeNode(root.left);
			PrePrintTreeNode(root.right);
		}
	}
	//先序遍历(非递归)
	public void PrePrintTreeNode2(TreeNode root){
		TreeNode p=root;
		Stack <TreeNode> stack=new Stack<TreeNode>();
		while(p!=null||!stack.isEmpty()){
			if(p!=null){
				stack.push(p);
				System.out.println(p.val);
				p=p.left;
			}
			else {
				p=stack.pop();
				p=p.right;
			}
		}
	}
	//中序遍历(递归)
	public void MidPrintTreeNode(TreeNode root){
		if(root!=null){
			MidPrintTreeNode(root.left);
			System.out.println(root.val);
			MidPrintTreeNode(root.right);
		}
	}
	//中序遍历(非递归)
	public void MidPrintTreeNode2(TreeNode root){
		TreeNode p=root;
		Stack <TreeNode> stack=new Stack<TreeNode>();
		while(p!=null||!stack.isEmpty()){
			if(p!=null){
				stack.push(p);
				p=p.left;
			}
			else {
				p=stack.pop();
				System.out.println(p.val);
				p=p.right;
			}
		}
	}
	//后序遍历(递归)
	public void BehPrintTreeNode(TreeNode root){
		if(root!=null){
			BehPrintTreeNode(root.left);
			BehPrintTreeNode(root.right);
			System.out.println(root.val);
		}
	}
	//后序遍历(非递归)
	public void BehPrintTreeNode(TreeNode root){
		if(root!=null){
			Stack <TreeNode> stack=new Stack<TreeNode>();
			for(TreeNode node=root;!stack.Empty();node!=null;){
				while(root!=null){
					stack.push(root);
					root=root.left;
				}
				while(!stack.empty()&& root==stack.peek().right){
					root=stack.pop();
					System.out.println(root.val);
				}
				if(stack.empty())return;
				else root=stack.peek().right();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值