Skip to content

Instantly share code, notes, and snippets.

@xynophon
Created July 10, 2015 05:04
Show Gist options
  • Select an option

  • Save xynophon/58434633b83640b0ab28 to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/58434633b83640b0ab28 to your computer and use it in GitHub Desktop.
LeetCode Invert Binary Tree
import java.util.*;
public class InvertBinaryTree {
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// recursive 300ms
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
// iterative 304ms
public TreeNode invertTree(TreeNode root) {
if(root == null) return root;
Stack<TreeNode> t = new Stack<>();
t.push(root);
while(!t.isEmpty()){
TreeNode n = t.pop();
TreeNode tmp = n.left;
n.left = n.right;
n.right = tmp;
if(n.right != null)
t.push(n.right);
if(n.left != null)
t.push(n.left);
}
return root;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment