![]() |
VOOZH | about |
Given a string that contains ternary expressions. The expressions may be nested, task is convert the given ternary expression to a binary Tree.
Examples:
Input : string expression = a?b:c
Output : a
/ \
b c
Input : expression = a?b?c:d:e
Output : a
/ \
b e
/ \
c d
Asked In : Facebook Interview
Idea is that we traverse a string make first character as root and do following step recursively .
- If we see Symbol '?'
- then we add next character as the left child of root.
- If we see Symbol ':'
- then we add it as the right child of current root.
do this process until we traverse all element of "String".
Below is the implementation of above idea
a b c d e
Time Complexity : O(n) [ here n is length of String ]
Auxiliary Space:O(n)
Here is the implementation of above approach:-
a b c d e
Time complexity: O(n) - Since we visit each character of the expression exactly once.
Space complexity: O(n) - Since in the worst case, the recursion stack can grow to the height of the tree, which can be O(n) if the ternary expression is a degenerate tree (a long chain of '?'). Additionally, we store O(n) nodes in the binary tree.