面试题27: 二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:先前序遍历这棵树的每个节点,如果遍历到的节点有子节点,就交换它的两个子节点。当交换完所有非叶节点的左、右子节点之后,就得到了树的镜像。
/*
1,非递归
*/
import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.empty()) {
TreeNode node = stack.pop();
if(node.left != null || node.right != null) {
TreeNode nodeLeft = node.left;
TreeNode nodeRight = node.right;
node.left = nodeRight;
node.right = nodeLeft;
}
if(node.left != null) stack.push(node.left);
if(node.right != null) stack.push(node.right);
}
}
}
/* 2 递归
时间复杂度O(n)
空间复杂度O(n)
*/
import java.util.*;
public class Solution {
public void Mirror(TreeNode root) {
if(root!=null){
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);
}
}
}
}