题解 | #二叉搜索树#
二叉搜索树
https://www.nowcoder.com/practice/3d6dd9a58d5246f29f71683346bb8f1b
class Tnode:#树的结构定义 def __init__(self, data, left: None, right: None): self.data = data self.left = left self.right = right def sea(T: Tnode, v: int):#构造二叉搜索树 if T == None: return if v < T.data: if T.left == None: T.left = Tnode(v, None, None) else: sea(T.left, v) if v > T.data: if T.right == None: T.right = Tnode(v, None, None) else: sea(T.right, v) #通过前序和中序判断是否为一棵树 def qx(T: Tnode, q: list): if T == None: return q.append(T.data) qx(T.left, q) qx(T.right, q) def mid(T: Tnode, mi: list): if T == None: return mid(T.left, mi) mi.append(T.data) mid(T.right, mi) n = int(input()) s_t = list(input()) s_T = Tnode(s_t[0], None, None) s_pr, s_mi = [], [] for k in range(1, len(s_t)): sea(s_T, s_t[k]) qx(s_T, s_pr) mid(s_T, s_mi) ans = [] for i in range(n): t = list(input()) T = Tnode(t[0], None, None) for j in range(1, len(t)): sea(T, t[j]) pr, mi = [], [] qx(T, pr) mid(T, mi) if s_mi == mi and s_pr == pr: ans.append("YES") else: ans.append("NO") for x in ans: print(x)