![]() |
Given a string str that contains a ternary expression which may be nested. The task is to convert the given ternary expression to a binary tree and return the root. Input: str = "a?b:c" Output: a b c a / \ b c The preorder traversal of the above tree is a b c. Input: str = "a?b?c:d:e" Output: a b c d e a / \ b e / \ c d
Approach: This is a stack-based approach to the given problem. Since the ternary operator has associativity from right-to-left, the string can be traversed from right to left. Take the letters one by one skipping the letters ‘?’ and ‘:’ as these letters are used to decide whether the current letter (alphabet [a to z]) will go into the stack or be used to pop the top 2 elements from the top of the stack to make them the children of the current letter which is then itself pushed into the stack. This forms the tree in a bottom-up manner and the last remaining element in the stack after the entire string is processed is the root of the tree. C++
Java
Python3
C#
Javascript
Output:
a b c d e
Time Complexity: O(n) Auxiliary Space: O(n) because using stack s |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |