Sword refers to Offer 27 (tree 3). Mirror image of binary tree
Problem Description:
Please complete a function that takes as input a binary tree and the function outputs its mirror image.
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
example:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
Problem-solving ideas:Idea link
1.use recursion
Binary tree image definition: For any node root in the binary tree, set its left/right child nodes to be left and right respectively; then in the mirror image of the binary tree, its left/right child nodes are respectively right and left.
Recursive parsing :
Termination condition : When the node root is empty (that is, beyond the leaf node), then return null;
Recursive work :
- Initialize the node tmp, which is used to temporarily store the left child node of root;
- Open the recursive right child node mirrorTree(root.right), and use the return value as the left child node of root.
- Turn on the recursive left child node mirrorTree(tmp) and use the return value as the right child node of root.
Return value: Return the current node root;
Implemented using recursive code:
/**
* 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;
}
}
2.Use auxiliary stack (queue implementation)
Use the stack (or queue) to traverse all the nodes node of the tree, and exchange the left/right child nodes of each node.
Algorithm flow :
- Special case handling: when the root is empty, return null directly;
- Initialization: stack (or queue), the queue is used in this article, and the root node root is added.
- Loop exchange: jump out when the queue queue is empty;
- Out of the queue: denoted as node;
- Add child nodes: enqueue the left and right child nodes of node;
- Swap: Swap the left/right children of node.
- Return value: Return the root node root.
Implemented using recursive code
/**
* 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<>();
//将root树中的根结点放到队列中
queue.offer(root);
TreeNode treeNode;
while(!queue.isEmpty()){
//弹出根节点
TreeNode node = queue.poll();
//将左右子节点放到队列中
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
//交换左右子节点,得到影像树
treeNode = node.left;
node.left = node.right;
node.right = treeNode;
}
return root;
}
}