1. 题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
2. 解题思路
(1)从输入描述可以看的出来,树的结构是左右子树交换了位置。这个时候就可以看作三个结点的根节点的左右交换的问题,然后递归即可。
(2)非递归实现.
3. 代码实现
(1)
public class Solution {
public void Mirror(TreeNode root) {
if (root == null)
return;
swap(root);
Mirror(root.left);
Mirror(root.right);
}
private void swap(TreeNode root){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
(2)非递归实现
public class Solution {
public void Mirror(TreeNode root) {
if (root == null)
return;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()){
while (root != null){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
stack.push(root);
//先左
root = root.left;
}
if(!stack.isEmpty()){
root = stack.pop();
//后右
root = root.right;
}
}
}
}