构建有序二叉树有两种构建方法:
1、有序插入 (大于根节点放右边 小于根节点放左边)
2、使用递归
1.有序插入
新建TreeNode节点
public class TreeNode {
public TreeNode lc;//左子树
public TreeNode rc;//右子树
public Integer value;//插入的值
public TreeNode(Integer value) {
this.value = value;
}
}
新建BinaryTree
public class BinaryTree<T> {
// 定义当前整棵树的记录
public TreeNode root;
// 方法
public void insert(Integer value) {
// 新建一个节点
TreeNode newNode = new TreeNode(value);
if (root == null) {
root = newNode;
return;
}
// 定义指针进行遍历;
TreeNode Node = root;
// 定义新的指针,记录Node上一个地址
TreeNode pNode;
while (true) {
pNode = Node;
if (newNode.value > Node.value) {
//往右放
Node = Node.rc;
if (Node == null) {
pNode.rc = newNode;
return;
}
} else