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))