剑指 Offer 27. 二叉树的镜像
题目:
思路:
直接递归,没啥说的
题解:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
dorevers(root);
return root;
}
private void dorevers(TreeNode root) {
if (root == null) {
return;
}
TreeNode temp;
if (root.left == null && root.right == null) {
return;
} else {
temp = root.left;
root.left = root.right;
root.right = temp;
}
dorevers(root.left);
dorevers(root.right);
}
}
优化后:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
dorevers(root);
return root;
}
private void dorevers(TreeNode root) {
if (root == null || (root.left == null && root.right == null)) {
return;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
dorevers(root.left);
dorevers(root.right);
}
}