Problem Description
Operate the given binary tree and transform it into a mirror image of the source binary tree.
Input description:
Input a binary tree
Output description:
output the mirror image of the binary tree
Example
Example 1
enter
Output
Solutions
analysis
- Realize the exchange of left and right subtrees through recursion, which can be bottom-up or top-down
method
- Bottom-up exchange via recursion
Code
public class Solution {
public void Mirror(TreeNode root) {
if (root == null) {
return;
}
// 临时变量存储
TreeNode left = root.left;
TreeNode right = root.right;
// 递归
Mirror(left);
Mirror(right);
// 交换
root.left = right;
root.right = left;
}
}
If you want to test, you can go directly to the link of Niuke.com to do the test