题目描述:
请完成一个函数,输入一个二叉树,该函数输出它的镜像
思路:只能想到递归
1)递归:自己的思路是对的!先在一个封装的方法中,进行主体逻辑功能的实现,再进行结束条件的编写。
但是该题答案中并没有重新声明一个方法,直接再主要方法中进行递归,这是一个需要思考的问题,什么时候需要新声明一个方法进行 逻辑封装,什么时候直接递归就行。
自己代码:
class Solution {
//每个节点的左右节点都要交换
public TreeNode mirrorTree(TreeNode root) {
//如果根节点为空,直接返回空
if(root == null) return null;
reverse(root);
return root;
}
void reverse(TreeNode root){
//当两个子节点都空时,才结束递归
if(root.left == null && root.right == null) return;
//主要的交换逻辑
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
if(root.left != null) reverse(root.left);
if(root.right != null) reverse(root.right);
}
}
答案代码:
1)优化递归,没有重新声明方法!主要还是自己能想到的编写顺序的问题
class Solution {
//每个节点的左右节点都要交换
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
//主体的交换逻辑
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//这个应该是 DFS深度优先的概念,先一层层深入将左子节点的交换,再返回到右子节点
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
}
2) 栈或队列:虽然对了,但是不好用!和前面几个题使用队列是一样的性质
class Solution {
//每个节点的左右节点都要交换
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
//就是将每个节点的子节点都进行了换位,用栈或者队列都可以
Queue<TreeNode> stack = new LinkedList<>();
//Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while(!stack.isEmpty()){
TreeNode node = stack.poll();
//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 root;
}
}