Skip to content

Instantly share code, notes, and snippets.

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 jianminchen/d035ad168d21e1c03a6601e8c8f5db96 to your computer and use it in GitHub Desktop.
Save jianminchen/d035ad168d21e1c03a6601e8c8f5db96 to your computer and use it in GitHub Desktop.
30 minutes mock interview - written by the peer
convert infix expression to binary expression tree
for example, ((2 + 2)+3)
The solution written by the peer:
+
+ 3
1 2
stack (
+
+ 3
1 2
((1+2)+3)
+
+ 3
1 2
class Solution {
class Node {
public String value;
public Node left, right;
public Node(String value) {
this.value = value;
}
}
public Node convert(String s) {
int n = s.length();
if (n == 0) return null;
Deque<Node> stack = new LinkedList<>();
stack.addLast(new Node('+'));
for(int i = 1; i < n; i++) {
char ch = s.charAt(i);
if (ch == '(' || Character.isDigit(ch)) {
Node newNode = new Node(ch == '(' ? "+" : ch);
Node node = stack.peekLast();
if (node.left == null) node.left = newNode;
else if (node.right == null) node.right = newNode;
stack.addLast(newNode);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment