public class Node {
// 数据项
long data;
// 左节点
Node leftChild = null;
// 右节点
Node rightChild = null;
public Node(long data) {
super();
this.data = data;
}
public static void main(String[] args) {
/**
* 特别注意以下两种情况:
*
* 一种 更改的是指向
*
* 一种 更改的是指向对象的属性
*
* 特别是在 组合 的模式中,这堆东西特别容易出错
*/
//1
Node n1 = new Node(1);
Node n2 = n1;
n2 = new Node(10);
System.out.println(n1.data);//1
//2
Node n3 = n1;
n3.data = 5;
System.out.println(n1.data);//5
//1
Node current = n1;
current = current.leftChild;
current = n2;
System.out.println(n1.leftChild==n2);//false
//2
current = n1;
current.leftChild = n2;
System.out.println(n1.leftChild==n2);//true
/**
* 这就是为什么要 引入 Node parent的原因
*/
}
}
public class Tree {
// 根节点
public Node root = null;
// 插入
public void insert(long value) {
//封装
Node newNode =new Node(value);
//两个必须的变量
Node current=root;
Node parent;
if(root==null) root=newNode;
else{
//子树迭代
parent=current;
while(true){
if(current.data>value){
current=current.leftChild;
if(current==null){
parent.leftChild=newNode;
return ;
}
}else{
current=current.rightChild;
//
if(current==null){
parent.rightChild=newNode;
return;
}
}
}
}
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.insert(10);
tree.insert(15);
tree.insert(13);
tree.insert(3);
tree.insert(20);
System.out.println(tree.root.leftChild.data);
}
}
二叉树的Java实现
最新推荐文章于 2024-09-13 17:05:05 发布