题目
题解一:递归
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode left = invertTree(root.left);
TreeNode right = invertTree(root.right);
root.right = left;
root.left = right;
return root;
}
题解二:队列迭代
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode index = queue.poll();
TreeNode tmp = index.left;
index.left = index.right;
index.right = tmp;
if (index.left != null) {
queue.add(index.left);
}
if (index.right != null) {
queue.add(index.right);
}
}
return root;
}