Last active
August 29, 2015 14:09
-
-
Save fever324/72143f02b97103751a1d to your computer and use it in GitHub Desktop.
Symmetric 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
/* | |
Symmetric Tree | |
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). | |
For example, this binary tree is symmetric: | |
1 | |
/ \ | |
2 2 | |
/ \ / \ | |
3 4 4 3 | |
But the following is not: | |
1 | |
/ \ | |
2 2 | |
\ \ | |
3 3 | |
*/ | |
import java.util.Stack; | |
public class Solution{ | |
public boolean isSymmetric(TreeNode root) { | |
if (root == null) | |
return true; | |
Stack<TreeNode> s1 = new Stack<TreeNode>(); | |
Stack<TreeNode> s2 = new Stack<TreeNode>(); | |
s1.add(root.left); | |
s2.add(root.right); | |
while (!s1.isEmpty() || !s2.isEmpty()) { | |
TreeNode a = s1.pop(); | |
TreeNode b = s2.pop(); | |
if (a == null && b == null) | |
continue; | |
if (a == null || b == null) | |
return false; | |
if (a.val != b.val) | |
return false; | |
s1.add(a.left); | |
s1.add(a.right); | |
s2.add(b.right); | |
s2.add(b.left); | |
} | |
return true; | |
} | |
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