题目
操作给定的二叉树,将其变换为源二叉树的镜像。
分析:
使用递归:
终结条件: head == null
只有左孩子或右孩子或两者都有时,交换
递归操作
代码实现:
/**
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 tmp = root.left;
root.left = root.right;
root.right = tmp;
Mirror(root.left);
Mirror(root.right);
}
}
注: 所有的递归都可以用栈来实现非递归版。