VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-ternary-expression-binary-tree/

⇱ Convert Ternary Expression to a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert Ternary Expression to a Binary Tree

Last Updated : 14 Sep, 2023

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 . 

  1. If we see Symbol '?' 
    • then we add next character as the left child of root. 
  2. 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  


Output
a b c d e 

Time Complexity : O(n) [ here n is length of String ]
Auxiliary Space:O(n)

Approach for Converting Ternary Expression to Binary Tree.

  • The algorithm uses a recursive approach to build the tree in a top-down manner.
  • It starts with creating a new node for the current character at the current index.
  • If the next character is a '?', it means that the current node needs a left child. So, the algorithm calls itself recursively with the next index to create the left child of the current node.
  • If the next character is a ':', it means that the current node needs a right child. So, the algorithm calls itself recursively with the next index to create the right child of the current node.
  • Finally, the algorithm returns the root node of the binary tree.

Here is the implementation of above approach:-


Output
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.

Comment
Article Tags: