//
public class BinaryTree {
public static void main(String[] args) {
final int[] values = { 1, 3, 4, 5, 2, 8, 6, 7, 9, 0 };
//生成一个树根
Node root=new Node();
root.setValue(values[0]);
for (int i=1;i<values.length;i++){
createBinaryTree(root,values[i]);
}
//输出结果
inOrderTransval(root);
}
public static Node createBinaryTree(Node node, int value) {
//>=放在右边
if(value>=node.getValue()){
//父节点没有右节点
if(node.getRight()==null){
//生成一个右节点
node.setRight(new Node());
//给右节点赋值
node.getRight().setValue(value);
}else{
createBinaryTree(node.getRight(),value);
}
}
//小于同上
if(value<node.getValue()){
if(node.getLeft()==null){
node.setLeft(new Node());
node.getLeft().setValue(value);
}else{
createBinaryTree(node.getLeft(),value);
}
}
return node;
}
public static void inOrderTransval(Node node) {
if(node == null){
return;
}else{
//先输出左节点
inOrderTransval(node.getLeft());
//再输出当前节点
System.out.println(node.getValue());
//最后输出右节点
inOrderTransval(node.getRight());
}
}
}
//node对象
public class Node {
// 节点值
private int value;
// 左节点
private Node left;
// 右节点
private Node right;
}
java实现一个二叉树并中序遍历输出
最新推荐文章于 2022-04-11 16:55:04 发布