Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 12, 2017 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/4003f82fb3d65ba6cd4212d9ec6a042e to your computer and use it in GitHub Desktop.
Save InterviewBytes/4003f82fb3d65ba6cd4212d9ec6a042e to your computer and use it in GitHub Desktop.
Invert Tree
package com.interviewbytes.trees;
import java.util.Deque;
import java.util.LinkedList;
public class InvertTree {
public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
Deque<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
return root;
}
}
package com.interviewbytes.trees;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment