public class BinaryTree {
private Node root;//二叉树树根
private class Node {
private long data;// 数据域
private Node leftchild; // 当前节点的左结点
private Node rightNode;
public Node(long data) {
this.data = data;
}
@Override
public String toString() {
return String.valueOf(data);
}
}
public boolean add(long value) {
Node node = new Node(value);//新建结点【待插入到树中的节点】
//空树
if (root == null) {
root = node;//新添加的节点就是树根
return true;
}
Node parent= root ; //当前节点的父节点
Node current = root;//当前节点
for (;;) {
parent =current;//保留父节点
if (value<current.data) {
//左小:左子树查找
current = current.leftchild;
if (current == null) {
//已经找到插入的位置
parent.leftchild = node;
return true;
}
}else if (value>current.data) {
//左大:右子树查找
current = current.rightNode;
if (current == null) {
//已经找到插入的位置
parent.rightNode = node;
return true;
}
}else {
return false;
}
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.add(8);
tree.add(10);
tree.add(5);
tree.add(3);
tree.add(7);
tree.add(6);
System.out.println(tree.root);
System.out.println(tree.root.leftchild);
System.out.println(tree.root.rightNode);
System.out.println(tree.root.leftchild.leftchild);
System.out.println(tree.root.leftchild.rightNode);
System.out.println(tree.root.rightNode.leftchild);
System.out.println(tree.root.rightNode.rightNode);
}
}
binary tree
Guess you like
Origin blog.csdn.net/qq_42481940/article/details/109922254
Recommended
Ranking