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.
Below is the implementation of the above approach:
a b c d e
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Convert Ternary Expression to a Binary Tree
- Minimum swap required to convert binary tree to binary search tree
- Program to convert Infix notation to Expression Tree
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Convert a given Binary tree to a tree that holds Logical AND property
- Convert a given Binary tree to a tree that holds Logical OR property
- Postorder traversal of Binary Tree without recursion and without stack
- Convert a Binary Tree into its Mirror Tree
- Print leaf nodes in binary tree from left to right using one stack
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Reverse alternate levels of a perfect binary tree using Stack
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Convert left-right representation of a binary tree to down-right
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a given Binary Tree to Doubly Linked List | Set 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sh16011993