镜像二叉树 java实现_镜像二叉树(Java实现)

树的实现

节点类

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

小结

递归版本的思路类似于二叉树的深度优先遍历

非递归版本的思路类似于二叉树的广度优先遍历

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值