迭代版本:
` public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) {val = x;} } public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()) { TreeNode t = queue.poll(); TreeNode right = t.right; t.right = t.left; t.left = right; if (t.left != null) queue.offer(t.left); if (t.right != null) queue.offer(t.right); } return root; } } `递归版本:
` public class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode r = root.right; root.right = invertTree(root.left); root.left = invertTree(r); return root; } } `