题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
思路:
这里有个细节,我们发现,6节点的子节点在操作之后并没有发生变化,所以等会我们在交换的时候,交换的不是节点的数值,而是整个节点。
另外我们进行操作的是非叶节点,注意到这两条,代码基本就成型了。
/**
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;
if(root.left==null&&root.right==null)
return;
TreeNode tempNode = null;
tempNode = root.left;
root.left = root.right;
root.right = tempNode;
Mirror(root.left);
Mirror(root.right);
}
}