描述
操作给定的二叉树,将其变换为源二叉树的镜像。
比如: 源二叉树
源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
示例1
输入: {8,6,10,5,7,9,11}
返回值: {8,10,6,11,9,7,5}
代码1 递归
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public TreeNode Mirror (TreeNode pRoot) {
if (pRoot == null) {
return pRoot;
}
TreeNode temp = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = temp;
Mirror(pRoot.left);
Mirror(pRoot.right);
return pRoot;
}
}
代码2 辅助栈
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public TreeNode Mirror (TreeNode pRoot) {
if (pRoot == null) {
return pRoot;
}
Stack<TreeNode> stack = new Stack<>();
stack.add(pRoot);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null) {
stack.add(node.left);
}
if (node.right != null) {
stack.add(node.right);
}
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
return pRoot;
}
}