树的实现
节点类
class Node {
T data;
Node left = null;
Node right = null;
public Node(T data) {
this.data = data;
}
}
public class BinarySortTree {
Node root = null;
public boolean isEmpty() {
return root == null;
}
/**
* 添加节点
*
* @param data 添加的节点保存的数据
* @return void
*/
public void add(int data) {
Node node = new Node<>(data);
if (isEmpty()) {
root = node;
return;
}
Node cur = root;
while (true) {
if (node.data <= cur.data) {
if (cur.left == null) {
cur.left = node;
break;
} else {
cur = cur.left;
}
} else {
if (cur.right == null) {
cur.right = node;
break;
} else {
cur = cur.right;
}
}
}
}
public void breadthFirstTravel() {
if (isEmpty()) {
System.out.println("树为空");
return;
}
Queue> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node cur = queue.remove();
System.out.println(cur.data);
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
}
}
递归版本
算法思路
逐层交换每个根节点的左右子树
具体步骤
transToMirrorImageTree(Node root)
如果根节点非空,则交换左右子树
递归调用transToMirrorImageTree(子树根节点)
/**
* 转成镜像二叉树
* 递归版本: 只要根节点不为空, 就递归交换根节点的左右子树
*
* @param root 根节点
* @return void
*/
public void transToMirrorImageTree(Node root) {
// 当前根节点不为空
if (root != null) {
// 交换左右子树
Node node = root.left;
root.left = root.right;
root.right = node;
// 递归
transToMirrorImageTree(root.left);
transToMirrorImageTree(root.right);
}
}
非递归版本
算法思路
遍历每个非叶节点,将其左右子树对换
具体步骤
transToMirrorImageTree(Node root)
将根节点加入队列
只要队列不空,循环执行
弹出队首,交换队列首元素节点的左右子树
左右子树中非空的则加入队列
/**
* 转成镜像二叉树
* 非递归版本: 利用队列遍历每个非叶节点, 交换左右子树
*
* @param root 根节点
* @return void
*/
public void transToMirrorImageTree(Node root) {
if (root == null) {
return;
}
// 便于遍历所有非叶节点
Queue queue = new LinkedList<>();
// 将根节点加入队列
queue.add(root);
// 只要队列非空
while (!queue.isEmpty()) {
// 取出队首元素
Node cur = queue.remove();
// 交换左右子树
Node tmp = cur.left;
cur.left = cur.right;
cur.right = tmp;
// 将非空左右节点加入队列
if (cur.left != null) {
queue.add(cur.left);
}
if (cur.right != null) {
queue.add(cur.right);
}
}
}
测试
创建二叉排序树并添加节点
调用镜像方法并输出
public static void main(String[] args) {
BinarySortTree tree = new BinarySortTree();
tree.add(4);
tree.add(2);
tree.add(13);
tree.add(3);
tree.add(5);
tree.breadthFirstTravel();
tree.transToMirrorImageTree(tree.root);
tree.breadthFirstTravel();
}
原二叉树广度优先遍历:4,2,13,3,5
镜像二叉树广度优先遍历:4,13,2,5,3
小结
递归版本的思路类似于二叉树的深度优先遍历
非递归版本的思路类似于二叉树的广度优先遍历