非递归法解题思路
二叉树的镜像
http://www.nowcoder.com/questionTerminal/564f4c26aa584921bc75623e48ca3011
看到题解里都是简单的递归方法,由于面试中面试官多会问非递归的方法,这里提供非递归的代码。供参考。
思路:镜像就是将“根”节点的左右两个“子”节点互换,类似于数组的元素交换(运用临时节点temp)
利用二叉树的广度优先搜索即可
public void Mirror(TreeNode root) {
if(root == null) return;
Queue<TreeNode> nodes = new LinkedList<>();
TreeNode curr, temp;
nodes.offer(root);
while(!nodes.isEmpty()){
int len = nodes.size();
for(int i = 0; i < len; i++){
curr = nodes.poll();
temp = curr.left;
curr.left = curr.right;
curr.right = temp;
if(curr.left != null) nodes.offer(curr.left);
if(curr.right != null) nodes.offer(curr.right);
}
}
}
