链表实现二叉树的类型声明(Java):
/**
* 树结构
*/
public class TreeNode {
int value;
TreeNode leftTreeNode = null;
TreeNode rightTreeNode = null;
public TreeNode(int value) {
this.value = value;
this.leftTreeNode = null;
this.rightTreeNode = null;
}
}
二叉树的构建
public class BinaryTree {
private TreeNode rootNode;//二叉树的根节点
public BinaryTree(int[] data) {
for (int i = 0; i < data.length; i++) {
addNodeToTree(data[I]);
}
}
//将指定的值加入到二叉树中的适当的节点
private void addNodeToTree(int value) {
TreeNode currentNode = rootNode;
if (rootNode == null) {//表示没有根节点,建立根节点
rootNode = new TreeNode(value);
return;
}
//建立二叉树
while (true) {
if (value < currentNode.value) {//在左子树
if (currentNode.leftTreeNode == null) {
currentNode.leftTreeNode = new TreeNode(value);
return;
} else {
currentNode = currentNode.leftTreeNode;
}
} else {//在右子树
if (currentNode.rightTreeNode == null) {
currentNode.rightTreeNode = new TreeNode(value);
return;
} else {
currentNode = currentNode.rightTreeNode;
}
}
}
}
}
调用(Kotlin写法):
var data: IntArray = intArrayOf(6, 3, 5, 9, 7, 8, 4, 2)
BinaryTree(data)
二叉树构建过程分解:
第一步:i = 0 ,value = 6 , rootNode = null 创建一个value=6的节点,rootNode = 6