题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
解析:交换每个节点左右子树的位置(非递归)
Java代码:
import java.util.*;
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;
}
}
}
}
递归的方法:
import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){//根节点为空直接返回
return;
}
if(root.left == null && root.right == null){//根节点的左右子节点为空直接返回
return;
}
//交换个根节点的左右子节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//递归
if(root.left != null){
Mirror(root.left);
}
if(root.right != null){
Mirror(root.right);
}
}
}