Skip to content

Instantly share code, notes, and snippets.

@Drup
Created October 1, 2020 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drup/363e745d20329cfbe3d8a6953413daa4 to your computer and use it in GitHub Desktop.
Save Drup/363e745d20329cfbe3d8a6953413daa4 to your computer and use it in GitHub Desktop.
from TreeVisitor import TreeVisitor
class MyTreeVisitor(TreeVisitor):
def visitLeaf(self, ctx):
return True # une feuille est un A.B.
def visitNode(self, ctx):
children = ctx.int_tree()
if not (len(children) == 2):
return False
else:
for tree in children:
if not self.visit(tree):
return False
return True
def visitTop(self, ctx):
thetree = ctx.int_tree()
return self.visit(thetree)
grammar Tree;
int_tree_top : int_tree EOF #top
;
int_tree: INT #leaf
| '(' INT int_tree+ ')' #node
;
INT: [0-9]+;
WS : (' '|'\t'|'\n')+ -> skip;
from TreeLexer import TreeLexer
from TreeParser import TreeParser
from MyTreeVisitor import MyTreeVisitor
from antlr4 import InputStream, CommonTokenStream
import sys
def main():
lexer = TreeLexer(InputStream(sys.stdin.read()))
stream = CommonTokenStream(lexer)
parser = TreeParser(stream)
tree = parser.int_tree_top()
print(tree)
visitor = MyTreeVisitor()
b = visitor.visit(tree)
print("Is it a binary tree ? "+str(b))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment