创建查找二叉树

import java.util.Scanner;

public class SearchBinaryTree {
	private TreeNode root;

	public SearchBinaryTree() {
		
	}
	
	/*
	 * 创建查找二叉树
	 */
	public TreeNode put(int data){
		TreeNode node = null;
		TreeNode parent = null; //用于记录父结点
		
		if(root == null){
			node = new TreeNode(0,data);//创建根节点,下标不设置(暂时为0)
			root = node;
			return node;//只是创建根节点,就直接可以返回了
		}
		node = root;//从根节点 比较
		while(node != null){
			parent = node;
			if(data > node.data){
				node = node.rightChild;
			}else if(data < node.data){
				node = node.leftChild;
			}else{
				System.out.println("cant`t add duplicate value!");
				return node;
			}
		}
		
		//表示将此节点添加到相应的位置
		node = new TreeNode(0,data);
		if(data < parent.data){
			parent.leftChild = node;
		}else{
			parent.rightChild = node;
		}
		node.parent = parent;  //上面父亲认了孩子,那么这里孩子也要认他的爹
		return node;
	}

	//中序遍历进行测试
	public void midOrder(TreeNode node){
		if(node == null)
			return;
		else{
			midOrder(node.leftChild);
			System.out.print(node.getData()+" ");
			midOrder(node.rightChild);
		}
	}
	
	public static void main(String[] args) {
		SearchBinaryTree binaryTree = new SearchBinaryTree();
		int[] intArray = new int[]{50,30,20,44,88,33,87,16,17,77};
		for(int i : intArray){
			binaryTree.put(i);
		}
		
		//中序遍历     排好后是正序
		binaryTree.midOrder(binaryTree.root);
		
	}

	class TreeNode {
		private int key;
		private TreeNode leftChild;
		private TreeNode rightChild;
		private TreeNode parent;
		private int data;
		public TreeNode(int key, int data) {
			super();
			this.key = key;
			this.leftChild = null;
			this.rightChild = null;
			this.parent = null;
			this.data = data;
		}
		public int getKey() {
			return key;
		}
		public void setKey(int key) {
			this.key = key;
		}
		public TreeNode getLeftChild() {
			return leftChild;
		}
		public void setLeftChild(TreeNode leftChild) {
			this.leftChild = leftChild;
		}
		public TreeNode getRightChild() {
			return rightChild;
		}
		public void setRightChild(TreeNode rightChild) {
			this.rightChild = rightChild;
		}
		public TreeNode getParent() {
			return parent;
		}
		public void setParent(TreeNode parent) {
			this.parent = parent;
		}
		public int getData() {
			return data;
		}
		public void setData(int data) {
			this.data = data;
		}
		
		
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值