描述
操作给定的二叉树,将其变换为源二叉树的镜像。
数据范围:二叉树的节点数 0 \le n \le 10000≤n≤1000 , 二叉树每个节点的值 0\le val \le 10000≤val≤1000
要求: 空间复杂度 O(n)O(n) 。本题也有原地操作,即空间复杂度 O(1)O(1) 的解法,时间复杂度 O(n)O(n)
比如:
源二叉树
镜像二叉树
我的思路
这不就是我之前之字型做错的思路吗?把节点交换打印出来就好。写着写着发现和那道题不一样,因为这道题目是不需要存储到另一个数据结构的,所以只需要修改节点就好啦。所以就写了一个递归。
乱写的,通过了。
//镜像二叉树
public TreeNode Mirror (TreeNode pRoot) {
// write code here
//要返回头结点是吧,那存储一下
TreeNode head = pRoot;
if (pRoot == null)
return null;
/*Queue<TreeNode> queue = new LinkedList<>();
queue.add(pRoot);
while (!queue.isEmpty()){
if (pRoot.left != null ||pRoot.right != null){
TreeNode temp = pRoot.left;
pRoot.left = pRoot.right;
pRoot.right = temp;
}
}*/
//我感觉啊,要用递归
exchange(pRoot);
return head;
}
private void exchange(TreeNode root) {
if (root == null)
return;
if (root.left != null ||root.right != null){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
exchange(root.right);
exchange(root.left);
}