二叉树遍历

二叉树的遍历: 
//创建二叉树
public class BinaryTree {
int data; // 根节点数据
BinaryTree left; // 左子节点
BinaryTree right; // 右子节点


public BinaryTree(int data) { // 实例化二叉树类
this.data = data;
left = null;
right = null;
}


public void insert(BinaryTree root, int data) { // 向二叉树中插入子节点
if (data > root.data) { // 二叉树的左节点都比根节点小
//因为一开始判断的就是 传入的节点如果比根节点大的话 那就是只能插入到右子节点
//所以这个地方判断一下根节点的子节点  如果不存在就 重新new一个节点给根节点的右子节点
//如果存在的话 说明根节点的右子节点已经有了 这个时候就需要重新判断一下 右子节点跟 新建节点大小比较了
if (root.right == null) {
root.right = new BinaryTree(data);
} else {
this.insert(root.right, data);
}
} else { // 二叉树的右节点都比根节点大
if (root.left == null) {
root.left = new BinaryTree(data);
} else {
this.insert(root.left, data);
}
}
}
}


/**
 * 遍历二叉树 实现二叉树的先根遍历,中根遍历,后根遍历
 * 
 * 
 */
public class BinaryTreePreorder {
public static void preOrder(BinaryTree root) { // 先根遍历
//从根节点遍历-遍历完左子节点-遍历右子节点
if (root != null) {
System.out.print(root.data + "-");
preOrder(root.left);
preOrder(root.right);
}
}


public static void inOrder(BinaryTree root) { // 中根遍历
//从小到大的遍历
if (root != null) {
inOrder(root.left);
System.out.print(root.data + "--");
inOrder(root.right);
}
}


public static void postOrder(BinaryTree root) { // 后根遍历
//从左到右的遍历
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data + "---");
}
}


public static void main(String[] str) {
int[] array = { 12, 76, 35, 22, 16, 48, 90, 46, 9, 40 };


BinaryTree root = new BinaryTree(array[0]); // 创建二叉树


for (int i = 1; i < array.length; i++) {
root.insert(root, array[i]); // 向二叉树中插入数据
}

System.out.println("先根遍历:");
preOrder(root);
System.out.println();

System.out.println("中根遍历:");
inOrder(root);
System.out.println();

System.out.println("后根遍历:");
postOrder(root);
System.out.println();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值