请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
- 0 <= 节点个数 <= 1000
分析:
这道题的思路就在于交换一个节点的节点的左右节点,然后再交换下一个节点的左右节点,重点在于遍历这些节点,我想到的有广度优先搜索(BFS)和深度优先搜索(DFS)。
方法1:BFS+队列
时间复杂度: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;
}
//创建队列
Deque<TreeNode> queue = new ArrayDeque<>();
//入栈头节点
queue.offerLast(root);
while(!queue.isEmpty()){
//出栈一个节点
TreeNode node = queue.pollFirst();
//交换左右节点
TreeNode left = node.left;
node.left = node.right;
node.right = left;
//入栈左右节点
if(node.left != null){
queue.offerLast(node.left);
}
if(node.right != null){
queue.offerLast(node.right);
}
}
return root;
}
}
方法2:DFS+递归
时间复杂度: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 left = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(left);
return root;
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof