Java实现二叉树

时间:2022-11-17 17:31:02
package BinaryTree;

public class main {

public static void main(String[] args) {
Node<String> nodes = initTree();
visit(nodes);// 遍历二叉树
System.out.println("=======================");
invert(nodes);
visit(nodes);
}

private static void invert(Node<String> node) {// 左右反转二叉树
if (node.leftTree != null || node.rightTree != null) {
Node<String> temp = node.leftTree;
node.leftTree = node.rightTree;
node.rightTree = temp;
invert(node.leftTree);// 遍历左子树
invert(node.rightTree);// 遍历右子树
}
}

private static void visit(Node<String> node) {// 中序遍历
if (node != null) {
visit(node.leftTree);// 遍历左子树
System.out.println(node.data);// 动作
visit(node.rightTree);// 遍历右子树
}
}

private static Node<String> initTree() {
Node<String> nodes = new Node<String>("shun");// 根结点
Node<String> node1 = new Node<String>("shun1");
Node<String> node2 = new Node<String>("shun2");
nodes.leftTree = node1;// 添加子节点到根结点
nodes.rightTree = node2;
node1.leftTree = new Node<String>("shun11");// 给node1添加子节点
node1.rightTree = new Node<String>("shun12");
node2.leftTree = new Node<String>("shun21");
node2.rightTree = new Node<String>("shun22");
return nodes;
}

}



// 节点类
package BinaryTree;

public class Node<T> {// T(type)表示泛型
public T data;
public Node<T> leftTree;
public Node<T> rightTree;

Node(T data){
this.data = data;
this.leftTree = null;
this.rightTree = null;
}
}