zoom笔试
zoom笔试,二叉树那题,写个python版的,给大家参考下吧,感觉有点难度啊
#ZOOM笔试##zoom校招##Zoom##二叉树#
# -*- coding: utf-8 -*- """ Created on Tue Aug 9 09:25:15 2022 @author: MI """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def findNode(node: int): res = [] for x in q: if node in x: res.append(x[0]) res.append(x[1]) res.remove(node) return res def preorder(node, head): if head.val == node: return head if head.left != None: return preorder(node, head.left) if head.right != None: return preorder(node, head.right) def structTree(node: int, head: TreeNode): num = findNode(node) for x in num: if x in tree: num.remove(x) if len(num) == 0: return tmp = preorder(node, head) for x in num: if tmp.left == None: tmp.left = TreeNode(x) tree.append(x) else: tmp.right = TreeNode(x) tree.append(x) if len(num) > 1: structTree(num[0], head) structTree(num[1], head) elif len(num) == 1: structTree(num[0], head) def Findpath(root, target): global path if (root == None): return False if str[root.val - 1] == 'R': path.append(1) else: path.append(-1) if (root.val == target): return True if (Findpath(root.left, target)): return True if (Findpath(root.right, target)): return True path.pop() return False if __name__ == '__main__': n = int(input()) str = input() q = [] for i in range(n - 1): q.append(list(map(int, input().rstrip().split()))) head = TreeNode(1) tree = [] tree.append(1) structTree(1, head) res = [] for x in tree: path = [] Findpath(head, x) res.append(abs(sum(path))) print(sum(res))
#ZOOM笔试##zoom校招##Zoom##二叉树#