226. Invert Binary Tree#

 1public TreeNode invertTree(TreeNode root) {
 2  if (root == null) return root;
 3
 4  TreeNode tmpLeft = root.left;
 5  root.left = root.right;
 6  root.right = tmpLeft;
 7
 8  invertTree(root.left);
 9  invertTree(root.right);
10
11  return root;
12}
 1public TreeNode invertTree(TreeNode root) {
 2  if (root == null) return root;
 3
 4  Stack<TreeNode> stk = new Stack<>();
 5  stk.push(root);
 6
 7  while (!stk.isEmpty()) {
 8    TreeNode currentNode = stk.pop();
 9
10    TreeNode tmpLeft = currentNode.left;
11    currentNode.left = currentNode.right;
12    currentNode.right = tmpLeft;
13
14    if (currentNode.left != null) stk.push(currentNode.left);
15    if (currentNode.right != null) stk.push(currentNode.right);
16  }
17
18  return root;
19}