当前位置:  首页>> 技术小册>> 数据结构与算法(下)

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

  1. 源二叉树
  2. 8
  3. / \
  4. 6 10
  5. / \ / \
  6. 5 7 9 11
  7. 镜像二叉树
  8. 8
  9. / \
  10. 10 6
  11. / \ / \
  12. 11 9 7 5

解法

将根结点的左右孩子互换,之后递归左右孩子。

  1. /**
  2. * @author bingo
  3. * @since 2018/11/22
  4. */
  5. /*
  6. public class TreeNode {
  7. int val = 0;
  8. TreeNode left = null;
  9. TreeNode right = null;
  10. public TreeNode(int val) {
  11. this.val = val;
  12. }
  13. }
  14. */
  15. public class Solution {
  16. /**
  17. * 将二叉树转换为它的镜像
  18. * @param root 二叉树的根结点
  19. */
  20. public void Mirror(TreeNode root) {
  21. if (root == null || !hasChild(root)) {
  22. return;
  23. }
  24. TreeNode t = root.left;
  25. root.left = root.right;
  26. root.right = t;
  27. Mirror(root.left);
  28. Mirror(root.right);
  29. }
  30. private boolean hasChild(TreeNode root) {
  31. return root.left != null || root.right != null;
  32. }
  33. }

测试用例

  1. 功能测试(普通的二叉树;二叉树的所有结点都没有左/右子树;只有一个结点的二叉树);
  2. 特殊输入测试(二叉树的根结点为空指针)。

该分类下的相关小册推荐: