@Test public void invertTreeDFS() { TreeNode root0 = new TreeNode(0); TreeNode left1 = new TreeNode(1); TreeNode right1 = new TreeNode(2); TreeNode left21 = new TreeNode(21); TreeNode right22 = new TreeNode(22); TreeNode left23 = new TreeNode(23); TreeNode right24 = new TreeNode(24); root0.left = left1; root0.right = right1; left1.left = left21; left1.right = right22; right1.left = left23; right1.right = right24; assertEquals(24, root0.right.right.val); assertEquals(21, InvertBinaryTreeSolution.invertTreeDFS(root0).right.right.val); }
static TreeNode invertTreeDFS(TreeNode root) { if (root == null) return null; final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return root; }
InvertBinaryTreeSolution { static TreeNode invertTreeDFS(TreeNode root) { if (root == null) return null; final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return root; } }
InvertBinaryTreeSolution { static TreeNode invertTreeDFS(TreeNode root) { if (root == null) return null; final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return root; }  }
InvertBinaryTreeSolution { static TreeNode invertTreeDFS(TreeNode root) { if (root == null) return null; final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return root; }   }
InvertBinaryTreeSolution { static TreeNode invertTreeDFS(TreeNode root) { if (root == null) return null; final Deque<TreeNode> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { final TreeNode node = stack.pop(); final TreeNode left = node.left; node.left = node.right; node.right = left; if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return root; }    }