剑指 Offer 27. 二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
例子
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
菜鸡代码。。
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return root;
//利用层序遍历,在左右结点入队的时候交换。
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while (!q.isEmpty()) {
TreeNode temp = q.poll();
if (temp.left != null) {
q.add(temp.left);
}
if (temp.right != null) {
q.add(temp.right);
}
if (temp.left != null && temp.right != null) {
TreeNode node = temp.left;
temp.left = temp.right;
temp.right = node;
continue;
}
if (temp.left != null ) {
temp.right = temp.left;
temp.left = null;
continue;
}
if (temp.right != null ) {
temp.left = temp.right;
temp.right = null;
}
}
return root;
}
大佬代码。。
public TreeNode mirrorTree(TreeNode root) {
if (root == null)
return null;
TreeNode tmpNode = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmpNode);
return root;
}