class BTNode<E> {
//数据域
E data;
//左孩子
BTNode<E> lchild;
//右孩子
BTNode<E> rchild;
//结点的构造方法 两种
public BTNode(E data,BTNode<E> lchild,BTNode<E> rchild){
this.data = data;
this.lchild = lchild;
this.rchild = rchild;
}
public BTNode(E data){
this(data,null,null);
}
}
class LinkedBTree<E> {
//根节点
BTNode<E> root;
//构造方法
public LinkedBTree(E data) {
root = new BTNode<>(data);
}
/**
*@Description 添加节点 如果父节点为空,返回错误, 新建一个结点,将其作为父节点的左子树或者右子树
*@Param
* parent:父节点
* data: 结点数据
* isLeft: 是否为左子树 true为左子树 false 为右子树
*@Return BTNode
*/
public BTNode<E> add(BTNode<E> parent, E data, boolean isLeft) {
if (parent == null) {
throw new RuntimeException("结点为空");
}
//新建结点
BTNode<E> newNode = new BTNode<>(data);
//如果isLeft为true 则为左子树
if (isLeft) parent.lchild = newNode;
// false 代表是右子树
else parent.rchild = newNode;
//将新结点返回
return newNode;
}
/**
*@Description 先序遍历算法 根左右
*/
public void preOrderByRecursion(BTNode root) {
if (root == null) {
return;
}
System.out.print(root.data + " ");
preOrderByRecursion(root.lchild);
preOrderByRecursion(root.rchild);
}
/**
*@Description 中序遍历算法 左根右
*/
public void midOrderByRecursion(BTNode root) {
if (root == null) {
return;
}
midOrderByRecursion(root.lchild);
System.out.print(root.data + " ");
midOrderByRecursion(root.rchild);
}
/**
*@Description 后序遍历算法 左右根
*/
public void lastOrderByRecursion(BTNode root) {
if (root == null) {
return;
}
lastOrderByRecursion(root.lchild);
lastOrderByRecursion(root.rchild);
System.out.print(root.data + " ");
}
/**
*@Description 遍历交换结点 全部交换
*/
public void swapTree(BTNode root) {
if (root != null) {
BTNode temp = root.lchild;
root.lchild = root.rchild;
root.rchild = temp;
swapTree(root.lchild);
swapTree(root.rchild);
}
}
}
public class BTreeTest{
public static void main(String[] args) {
LinkedBTree linkedBTree = new LinkedBTree('A');
BTNode root = linkedBTree.root;
BTNode nodeB = linkedBTree.add(root,'B',true);
BTNode nodeC = linkedBTree.add(root,'C',false);
BTNode nodeD = linkedBTree.add(nodeB,'D',true);
BTNode nodeE = linkedBTree.add(nodeB,'E',false);
BTNode nodeF = linkedBTree.add(nodeC,'F',false);
BTNode nodeG = linkedBTree.add(nodeE,'G',true);
System.out.println("====中序遍历=====");
linkedBTree.midOrderByRecursion(root);
System.out.println();
System.out.println("====先序遍历====");
linkedBTree.preOrderByRecursion(root);
System.out.println();
System.out.println("=====后序遍历====");
linkedBTree.lastOrderByRecursion(root);
linkedBTree.swapTree(root);
System.out.println();
System.out.println("=======转换后=======");
linkedBTree.preOrderByRecursion(root);
}
}
数据结构上机6
最新推荐文章于 2022-05-30 23:04:19 发布