题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011
解题想法
递归思路:交换其左右子树,然后递归调用,交换子树。
非递归思路:涉及到反转,就应该想到栈,使用栈进行反转交换
代码实现
- 递归版本
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if (root == null){
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
Mirror(root.left);
Mirror(root.right);
}
}
- 使用栈
import java.util.Stack;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
if(root == null){
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode rootTemp = stack.pop();
TreeNode temp1 = rootTemp.left;
rootTemp.left = rootTemp.right;
rootTemp.right = temp1;
if (rootTemp.left != null){
stack.push(rootTemp.left);
}
if (rootTemp.right != null){
stack.push(rootTemp.right);
}
}
}
}