特点
- 每个节点最多有两颗子树。
- 左子树和右子树是有顺序的,次序不能颠倒。
- 即使某节点只有一个子树,也要区分左右子树。
树图
伪代码实现
@Data
public class Node {
int value;
Node leftChild;
Node rightChild;
public Node(int value) {
this.value = value;
}
@Override
public String toString() {
return String.valueOf(value);
}
}
import java.util.ArrayList;
import java.util.List;
public class BinaryTree {
private Node root = null;
public BinaryTree(int value) {
root = new Node(value);
root.leftChild = null;
root.rightChild = null;
}
public BinaryTree() {
}
public Node getRoot() {
return root;
}
public boolean add(int value) {
boolean success = true;
Node node = new Node(value);
if (root == null) {
root = node;
root.leftChild = null;
root.rightChild = null;
} else {
Node current = root;
while (true) {
if (value < current.value) {
if (current.leftChild == null) {
current.leftChild = node;
break;
}
current = current.leftChild;
} else if (value > current.value) {
if (current.rightChild == null) {
current.rightChild = node;
break;
}
current = current.rightChild;
} else {
success = false;
break;
}
}
}
return success;
}
public Node get(int value) {
Node current = root;
while (true) {
if (value == current.value) {
return current;
} else if (value < current.value) {
current = current.leftChild;
} else if (value > current.value) {
current = current.rightChild;
}
if (current == null) {
return null;
}
}
}
public void inOrder(Node node) {
if (node != null) {
inOrder(node.getLeftChild());
System.out.println(node);
inOrder(node.getRightChild());
}
}
public void order2(Node node, List<Integer> list) {
if (node == null)
return;
order2(node.getLeftChild(), list);
list.add(node.getValue());
order2(node.getRightChild(), list);
}
@Override
public String toString() {
List<Integer> list = new ArrayList<>();
order2(root, list);
return list.toString();
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
binaryTree.add(3);
binaryTree.add(1);
binaryTree.add(0);
binaryTree.add(2);
binaryTree.add(7);
binaryTree.add(5);
binaryTree.add(8);
binaryTree.add(9);
System.out.println(binaryTree.toString());
Node root = binaryTree.getRoot();
binaryTree.inOrder(root);
}
}