Created
July 10, 2015 05:04
-
-
Save xynophon/58434633b83640b0ab28 to your computer and use it in GitHub Desktop.
LeetCode Invert Binary Tree
This file contains hidden or 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
| 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