Skip to content

Instantly share code, notes, and snippets.

@mwacc
Created July 10, 2013 10:24
Show Gist options
  • Save mwacc/5965225 to your computer and use it in GitHub Desktop.
Save mwacc/5965225 to your computer and use it in GitHub Desktop.
Check if tree is symmetric based on BFS algorithm
class Node {
def val
def left
def right
}
/*
root
A B
C D
F E
*/
Node root = new Node()
root.val = 'val'
Node A = new Node()
A.val = 'A'
Node B = new Node()
B.val = 'B'
Node C = new Node()
C.val = 'C'
Node D = new Node()
D.val = 'D'
Node F = new Node()
F.val = 'F'
Node E = new Node()
E.val = 'E'
root.left = A
root.right = B
A.right = C
B.left = D
C.left = F
D.right = E
// breadth first search
def bfs(Node n) {
Queue<Node> q = new LinkedList<Node>()
q.offer(n)
while( q.size() > 0 ) {
Node e = q.poll()
print "$e.val "
if(e.left != null) q.offer(e.left)
if(e.right != null) q.offer(e.right)
}
}
//bfs(root)
is_sym(root)
def is_sym(Node root) {
String leftSubTree = sym_bfs(root.left, "l", "r")
String rightSubTree = sym_bfs(root.right, "r", "l")
println "$leftSubTree vs $rightSubTree"
print leftSubTree.equals(rightSubTree)
}
def sym_bfs(Node n, String leftMark, String rightMark) {
StringBuilder str = new StringBuilder();
Queue<Node> q = new LinkedList<Node>()
q.offer(n)
while( q.size() > 0 ) {
Node e = q.poll()
if(e.left != null) {
str.append( leftMark)
q.offer(e.left)
}
if(e.right != null) {
str.append( rightMark )
q.offer(e.right)
}
}
return str.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment