二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/
2 7
/ \ /
1 3 6 9镜像输出:
4
/
7 2
/ \ /
9 6 3 1
题解
-
递归
- 思路
- 最终要的是找到二叉树镜像的规律
- 画图可以看出二叉树的镜像就是递归地交换二叉树的左右节点
- 复杂度分析
- 时间复杂度 O(n)
- 空间复杂度 O(n):最差的情况下(当二叉树退化为链表)需要使用 O(n)大小的栈空间
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode mirrorTree(TreeNode root) { if(root == null)return null; TreeNode temp = root.left; root.left = mirrorTree(root.right); root.right = mirrorTree(temp); return root; } }
- 思路
-
辅助队列(栈)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode mirrorTree(TreeNode root) { if(root == null)return null; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(queue.size() != 0){ TreeNode outStack = queue.poll(); TreeNode temp = outStack.right; if(outStack.left != null)queue.add(outStack.left); if(outStack.right != null)queue.add(outStack.right); outStack.right = outStack.left; outStack.left = temp; } return root; } }
总结
- 多画图,找规律
- 可以分解为交换左右子节点的问题,找到子问题自然找到递归的写法了。