Java 二叉查找树的插入及遍历的简单实现

1.何为二叉查找树?

(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;

(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;

(3)左、右子树也分别为二叉排序树;

(4)没有键值相等的结点。

2.二叉查找树的简单实现:

package com.hmi.test;

public class BinarySearchTree {
	int data; // 数据
	BinarySearchTree left; // 左二叉树
	BinarySearchTree right;// 右二叉树

	public BinarySearchTree(int data) {
		this.data = data;
		left = null;
		right = null;
	}

	/**
	 * 插入元素 
	 * @param root 根节点元素
	 * @param data 要插入的数据
	 */
	public void insert(BinarySearchTree root, int data) {
		if (root.data > data) {
			if (root.left != null) {
				insert(root.left, data);
			}
			if (root.left == null) {
				root.left = new BinarySearchTree(data);
			}
		} else if (root.data < data) {
			if (root.right != null) {
				insert(root.right, data);
			}
			if (root.right == null) {
				root.right = new BinarySearchTree(data);
			}
		}
	}

	/**
	 * 前序遍历
	 * @param root 根节点元素
	 */
	public void preOrder(BinarySearchTree root) {
		if (root != null) {
			System.out.print(root.data + " ");
			preOrder(root.left);
			preOrder(root.right);
		}
	}

	/**
	 * 中序遍历
	 * @param root 根节点元素
	 * 
	 */
	public void inOrder(BinarySearchTree root) {
		if (root != null) {
			inOrder(root.left);
			System.out.print(root.data + " ");
			inOrder(root.right);
		}
	}

	/**
	 * 后序遍历
	 * @param root 根节点元素
	 */
	public void postOrder(BinarySearchTree root) {
		if (root != null) {
			postOrder(root.left);
			postOrder(root.right);
			System.out.print(root.data + " ");
		}
	}
	public static void main(String[] args) {
		int []data = {34,16,45,24,10,56,36};
		BinarySearchTree root = new BinarySearchTree(data[0]);
		//循环插入二叉树
		for (int i = 1; i < data.length; i++) {
			root.insert(root, data[i]);
		}
		System.out.println("前序遍历为:");
		root.preOrder(root);
		System.out.println();
		System.out.println("中序遍历为:");
		root.inOrder(root);
		System.out.println();
		System.out.println("后序遍历为:");
		root.postOrder(root);
	}
}

运行结果:

数据就没用节点了,直接用的整型数据,二叉查找树数据的插入及遍历主要就是运用了递归的思想。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值