题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:
使用递归交换每个节点的左右子树位置。
代码:
package 二叉树的镜像;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
class Solution {
public void Mirror(TreeNode root) {
if (root == null) { // 为空直接返回
return;
}
TreeNode nodeTemp = null;
nodeTemp = root.left;
root.left = root.right;
root.right = nodeTemp;
Mirror(root.left); // 递归左子树
Mirror(root.right); // 递归右子树
}
}
/**
* 操作给定的二叉树,将其变换为源二叉树的镜像。
* @author Administrator
*/
public class Demo {
public static void main(String[] args) {
}
}