1. /**
    2. * 226. Invert Binary Tree
    3. * <p>
    4. * Given the root of a binary tree, invert the tree, and return its root.
    5. * <p>
    6. * <p>
    7. * <p>
    8. * Example 1:
    9. * <p>
    10. * <p>
    11. * Input: root = [4,2,7,1,3,6,9]
    12. * Output: [4,7,2,9,6,3,1]
    13. * Example 2:
    14. * <p>
    15. * <p>
    16. * Input: root = [2,1,3]
    17. * Output: [2,3,1]
    18. * Example 3:
    19. * <p>
    20. * Input: root = []
    21. * Output: []
    22. * <p>
    23. * <p>
    24. * Constraints:
    25. * <p>
    26. * The number of nodes in the tree is in the range [0, 100].
    27. * -100 <= Node.val <= 100
    28. */
    29. public class Lesson226 {
    30. public static void main(String[] args) {
    31. TreeNode root = Util.createTree(3);
    32. Util.printBeforeTree(root);
    33. new Solution().invertTree(root);
    34. System.out.println("\n------");
    35. Util.printBeforeTree(root);
    36. }
    37. /**
    38. * Definition for a binary tree node.
    39. */
    40. private static class Solution {
    41. public TreeNode invertTree(TreeNode root) {
    42. revert(root);
    43. return root;
    44. }
    45. private void revert(TreeNode node) {
    46. if (node == null) return;
    47. TreeNode tmp = node.left;
    48. node.left = node.right;
    49. node.right = tmp;
    50. revert(node.left);
    51. revert(node.right);
    52. }
    53. }
    54. private static class Solution2 {
    55. public TreeNode invertTree(TreeNode root) {
    56. LinkedList<TreeNode> list = new LinkedList<>();
    57. list.add(root);
    58. while(!list.isEmpty()) {
    59. TreeNode curNode = list.poll();
    60. TreeNode tmp = curNode.left;
    61. curNode.left = curNode.right;
    62. curNode.right = tmp;
    63. if (curNode.left != null) {
    64. list.add(curNode.left);
    65. }
    66. if (curNode.right != null) {
    67. list.add(curNode.right);
    68. }
    69. }
    70. return root;
    71. }
    72. }
    73. }