1
0
mirror of https://github.com/DanilaFe/abacus synced 2026-01-28 01:25:19 +00:00

Implement parsing a postfix expression into a tree.

This commit is contained in:
2017-07-25 14:21:00 -07:00
parent 3684673362
commit e4e9e2ce21
3 changed files with 82 additions and 1 deletions

View File

@@ -78,8 +78,26 @@ public abstract class TreeNode {
return output;
}
public static TreeNode fromString(String string){
public static TreeNode fromStringRecursive(String source, ArrayList<Match<TokenType>> matches){
if(matches.size() == 0) return null;
Match<TokenType> match = matches.remove(0);
if(match.getType() == TokenType.OP){
TreeNode right = fromStringRecursive(source, matches);
TreeNode left = fromStringRecursive(source, matches);
if(left == null || right == null) return null;
else return new OpNode(source.substring(match.getFrom(), match.getTo()), left, right);
} else if(match.getType() == TokenType.NUM){
return new NumberNode(Double.parseDouble(source.substring(match.getFrom(), match.getTo())));
}
return null;
}
public static TreeNode fromString(String string){
ArrayList<Match<TokenType>> matches = intoPostfix(string, tokenize(string));
if(matches == null) return null;
Collections.reverse(matches);
return fromStringRecursive(string, matches);
}
}