java_简单的写个二叉树

二叉树

一个根,然后就是左右孩纸,以左右孩纸为根再发展左右孩纸。。。

<span style="font-size:18px;">package com.vince;

public class BinaryTree {

	private Node root;

	public void AddNode(int data) {
		if (root == null) {
			root = new Node(data);
		} else {
			root.add(data);
		}
	}

	public void printNode() {
		if (root != null) {
			root.print();
		}
	}

	private class Node {
		private int data;
		private Node left;
		private Node right;

		public Node(int data) {
			// TODO 自动生成的构造函数存根
			this.data = data;
		}

		// 添加节点
		public void add(int data) {
			if (this.data > data) {
				if (this.left == null) {
					this.left = new Node(data);
				} else {
					this.left.add(data);
				}
			} else if (this.data <= data) {
				if (this.right == null) {
					this.right = new Node(data);
				} else {
					this.right.add(data);
				}
			}
		}

		// 根据中序遍历(左根右)
		public void print() {
			if (this.left != null) {
				this.left.print();
			}
			System.out.print(this.data + "->");
			if (this.right != null) {
				this.right.print();
			}
		}
	}
}</span>

很简单的数据结构

package com.vince;


/**
 * 二叉树
 * @author 97124
 *
 */
public class BinaryTreeDemo {


	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		BinaryTree bt = new BinaryTree();
		bt.AddNode(8);
		bt.AddNode(3);
		bt.AddNode(10);
		bt.AddNode(1);
		bt.AddNode(6);
		bt.AddNode(14);
		bt.AddNode(4);
		bt.AddNode(7);
		bt.AddNode(13);
		
		bt.printNode();
	}

}

主函数输入。。。看代码就能理解。。。当复习


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值