Convert Ternary Expression to Binary Tree

Given a string that contains ternary expressions. The expressions may be nested. You need to convert the given ternary expression to a binary Tree and return the root.

Input Format:
First line of input contains of test case T. The only line of test case consists of String s.

Outpu Format:
Preorder traversal of Tree formed

Your Task:
This is a function problem, you don't need to read input/output. Just complete the functionconvertExpression that take string and index(initialized from 0) as parameters.

Constraints:
1 <= T <= 100
1 <= |String| <= 100

Example:
Input:

2
a?b:c
a?b?c:d:e
Output:
a b c
a b c d e

Explanation:
Testcase1:

Input :  string expression =   a?b:c
Output : a
              /  \
             b    c
Testcase2:

Input : expression =  a?b?c:d:e
Output :   a
                /  \
              b    e
             /  \
            c    d

思路:

大问题可以拆成类型相同,而且size更小的小问题,所以可以用递归。

显然第一个元素一定是根节点的值,只要找到左右子树对应输入中的哪一部分,本题即可由递归轻松解决。

举例 对于testcase2,

a是根节点,

b?c:d 这部分输入对应的是根节点的左子树,

e 这部分输入对应根节点的右子树。

用两个变量question和colon统计当前问号和分号的个数,

当question为1的时候,当前下标 + 1是根节点左子树对应输入的起点,

当question == colon 的时候,当前下标-1 是根节点左子树对应输入的终点,当前下标 + 1 是根节点右子树对应输入的起点。

testcase1 = "a?b:c"
testcase2 = "a?b?c:d:e?f:g"

class TreeNode(object):
    def __init__(self, val):
        self.val = val
        self.left = None 
        self.right = None

def solution(s):
    if not s:
        return None 
    if len(s) == 1:
        return TreeNode(s[0])
    root = TreeNode(s[0])
    # print (s)
    question, colon = 0, 0
    for i in range(len(s)):
        # print(i, question, colon)
        if s[i] == "?":
            question += 1
            if question == 1:
                pos1 = i
        elif s[i] == ":":
            colon += 1
            if colon == question:
                pos2 = i 
                break
    # print (pos2)
    root.left = solution(s[pos1 + 1: pos2])
    root.right = solution(s[pos2 + 1:])

        
    return root

def inorder(root):
    if not root:
        return []
    return inorder(root.left) + [root.val] + inorder(root.right)

res = solution(testcase2)
print(inorder(res))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值