用二叉树实现排序

package com.huang;

public class NodeTree {

	public static void main(String [] args){
		int [ ] data = {8, 3, 10, 1, 6, 14, 4, 7};

		/* 实现 有序二叉树 */
		NodeTree nodeTree = new NodeTree();
		for(int i=0; i<data.length; i++){
			nodeTree.insert(data[i]);
		}
		nodeTree.inOrder();//输出中序遍历结果
		nodeTree.preOrder();//前序遍历
		nodeTree.postOrder();//后序遍历

	}

	private Node root;
	
	public NodeTree() {
		root = null;
	}
	
	//把data插入到二叉树中
	public void insert(int data) {
		if(root==null){
			root = new Node(data);
		}
		else {
			root.add(data);
		}
	}

    //中序遍历打印节点
	public void inOrder(){
	    System.out.print("中序遍历结果:");
	    root.printNode();
    }

	//前序遍历
	public void preOrder() {
	}

	//后序遍历
	public void postOrder() {
	}

	public class Node{
		public int data;
		public Node leftNode;
		public Node rightNode;
		
		public Node(int  data) {
			this.data = data;
			leftNode = null;
			rightNode = null;
			System.out.println("该节点赋值为:" + data);
		}

		//小于父节点则为左,大于父节点则为右
		public void add(int data){
			if(data < this.data){
				if(this.leftNode==null){
					this.leftNode = new Node(data) ;
				}
				else{//左孩子非空
					this.leftNode.add(data);
				}
			}

			else if(this.data <= data){
				if(this.rightNode==null){
					this.rightNode = new Node(data) ;
				}
				else{//右孩子非空
					this.rightNode.add(data);
				}
			}

		}

		//中续遍历   左 根 右
		public void printNode(){
            if(this.leftNode!=null ){
                this.leftNode.printNode();
            }
            System.out.print(this.data + " -> ");
            if(this.rightNode!=null ){
                this.rightNode.printNode();
            }
        }

	}
	
	
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城有术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值