-
-
Save InterviewBytes/4003f82fb3d65ba6cd4212d9ec6a042e to your computer and use it in GitHub Desktop.
Invert Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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