Java 二叉树算法
我遇到了以下算法,该算法将五个节点插入到二叉树中,然后遍历该树 正在创建什么样的树结构?它是平衡的还是不平衡的?你怎么知道?这会影响算法执行的遍历类型吗Java 二叉树算法,java,binary-tree,Java,Binary Tree,我遇到了以下算法,该算法将五个节点插入到二叉树中,然后遍历该树 正在创建什么样的树结构?它是平衡的还是不平衡的?你怎么知道?这会影响算法执行的遍历类型吗 import Prog1Tools.IOTools; class Node { Node left; Node right; int value; public Node(int value) { this.value = value; } } public class Genera
import Prog1Tools.IOTools;
class Node {
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
public class GeneralTreeTest {
public static void main(String[] args) {
// build a simple tree add 5 nodes to the tree
Node root = new Node(5);
System.out.println("Tree Example");
System.out.println("Building tree with root value " + root.value);
insert(root, 1);
insert(root, 8);
insert(root, 6);
insert(root, 3);
insert(root, 9);
System.out.println("Traversing tree ");
printOrder(root);
}
public static void insert(Node node, int value) {
if (value < node.value) {
if (node.left != null) {
insert(node.left, value);
} else {
System.out.println(" Inserted " + value + " to left of "
+ node.value);
node.left = new Node(value);
}
} else if (value > node.value) {
if (node.right != null) {
insert(node.right, value);
} else {
System.out.println(" Inserted " + value + " to right of "
+ node.value);
node.right = new Node(value);
}
}
}
public static void printOrder(Node node) {
if (node != null) {
printOrder(node.left);
System.out.println(" Traversed " + node.value);
printOrder(node.right);
}
}
}
导入Prog1Tools.IOTools;
类节点{
左淋巴结;
节点权;
int值;
公共节点(int值){
这个值=值;
}
}
公共类GeneralTreeTest{
公共静态void main(字符串[]args){
//构建一个简单的树向树中添加5个节点
节点根=新节点(5);
System.out.println(“树示例”);
System.out.println(“使用根值构建树”+root.value);
插入(根,1);
插入(根,8);
插入(根,6);
插入(根,3);
插入(根,9);
System.out.println(“遍历树”);
打印顺序(根);
}
公共静态void插入(节点,int值){
if(值<节点值){
if(node.left!=null){
插入(node.left,值);
}否则{
System.out.println(“插入的“+值+”位于”
+节点值);
node.left=新节点(值);
}
}else if(值>节点值){
if(node.right!=null){
插入(node.right,value);
}否则{
System.out.println(“插入的“+值+”到右侧”
+节点值);
node.right=新节点(值);
}
}
}
公共静态无效打印订单(节点){
如果(节点!=null){
printOrder(节点左);
System.out.println(“遍历”+节点值);
printOrder(节点右侧);
}
}
}
它是平衡的还是不平衡的
你没有任何平衡逻辑。例如,如果插入1、2、3,则所有节点都将继续向右。例如,在AVL平衡树中,1将“向左旋转”,2将成为根,从而平衡树
你怎么知道是一个还是另一个
可以在树中绘制节点数据结构的指针
这会影响算法正在执行的遍历类型
不应该。您当前正在向左打印,然后是向右打印根。同样的顺序也适用于任何类型的二叉树似乎是不平衡的。应该很容易查找平衡二叉树的定义,并绘制您创建的二叉树