/** * 226. Invert Binary Tree * <p> * Given the root of a binary tree, invert the tree, and return its root. * <p> * <p> * <p> * Example 1: * <p> * <p> * Input: root = [4,2,7,1,3,6,9] * Output: [4,7,2,9,6,3,1] * Example 2: * <p> * <p> * Input: root = [2,1,3] * Output: [2,3,1] * Example 3: * <p> * Input: root = [] * Output: [] * <p> * <p> * Constraints: * <p> * The number of nodes in the tree is in the range [0, 100]. * -100 <= Node.val <= 100 */public class Lesson226 { public static void main(String[] args) { TreeNode root = Util.createTree(3); Util.printBeforeTree(root); new Solution().invertTree(root); System.out.println("\n------"); Util.printBeforeTree(root); } /** * Definition for a binary tree node. */ private static class Solution { public TreeNode invertTree(TreeNode root) { revert(root); return root; } private void revert(TreeNode node) { if (node == null) return; TreeNode tmp = node.left; node.left = node.right; node.right = tmp; revert(node.left); revert(node.right); } } private static class Solution2 { public TreeNode invertTree(TreeNode root) { LinkedList<TreeNode> list = new LinkedList<>(); list.add(root); while(!list.isEmpty()) { TreeNode curNode = list.poll(); TreeNode tmp = curNode.left; curNode.left = curNode.right; curNode.right = tmp; if (curNode.left != null) { list.add(curNode.left); } if (curNode.right != null) { list.add(curNode.right); } } return root; } }}