一个简单二叉树及先序中序后续遍历的实现

本文深入探讨了二叉树的前序、中序和后序遍历算法,通过具体的代码实现展示了每种遍历方式的特点及应用。文章首先定义了二叉树节点的数据结构,然后构建了一个简单的二叉树实例,并使用递归方法实现了三种遍历方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package testcase;

class Node{
	private Object data;
	private Node leftChild;
	private Node rightChild;
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public Node getLeftChild() {
		return leftChild;
	}
	public void setLeftChild(Node leftChild) {
		this.leftChild = leftChild;
	}
	public Node getRightChild() {
		return rightChild;
	}
	public void setRightChild(Node rightChild) {
		this.rightChild = rightChild;
	}
	public Node(Object data) {
		super();
		this.data = data;
	}
}

public class BinTree {
	public static void main(String[] args) {
		Node n1=new Node(10);
		Node n2=new Node(9);
		Node n3=new Node(20);
		Node n4=new Node(15);
		Node n5=new Node(35);
		
		n1.setLeftChild(n2);
		n1.setRightChild(n3);
		n3.setLeftChild(n4);
		n3.setRightChild(n5);
		
		BinTree br=new BinTree();
		br.preOrder(n1);
		System.out.println();
		br.inOrder(n1);
		System.out.println();
		br.postOrder(n1);
	}
	public void preOrder(Node current){
		if(current!=null){
			System.out.print(current.getData()+" ");
			preOrder(current.getLeftChild());
			preOrder(current.getRightChild());
		}
	}
	public void inOrder(Node current){
		if(current!=null){
			inOrder(current.getLeftChild());
			System.out.print(current.getData()+" ");
			inOrder(current.getRightChild());
		}
	}
	public void postOrder(Node current){
		if(current!=null){
			postOrder(current.getRightChild());
			postOrder(current.getLeftChild());
			System.out.print(current.getData()+" ");
		}
	}
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值