题目
思路
非递归:利用队列。
根节点先入队。
循环入队,条件:队列不为空
(注意,LinkedList没有isEmpty()这个方法,判断队列不为空list.size()!=0)
弹出队首节点。
加入节点的左右孩子节点进队列中。
交换左右孩子。
递归:
root.left = mirrorTree(root.right);
root.right = mirrorTree(temp);
非常简单,就是一个递归交换左右孩子节点,因为二叉树本身就是递归定义的。
class Solution {
public TreeNode mirrorTree(TreeNode root) {
非递归
// if(root==null){
// return null;
// }
// LinkedList<TreeNode> queue=new LinkedList<>();
// queue.addLast(root);
// while(queue.size()!=0){
// //LinkedList没有isEmpty()这个方法
// TreeNode tr=new TreeNode();
// tr= queue.removeFirst();
// if(tr.left!=null)
// queue.addLast(tr.left);
// if(tr.right!=null)
// queue.addLast(tr.right);
// TreeNode tempNode=new TreeNode();
// tempNode=tr.left;
// tr.left=tr.right;
// tr.right=tempNode;
// }
// return root;
递归
if (root == null) return root;
TreeNode temp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(temp);
return root;
}
}