码迷,mamicode.com
首页 > 编程语言 > 详细

2018秋招小红书算法方向在线编程题

时间:2018-09-18 23:54:54      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:tle   rip   nbsp   node   str   lag   分享   dtree   spl   

技术分享图片

技术分享图片

代码如下:

class TreeNode:
    def __init__(self, x):
        self.left=None
        self.right=None
        self.value=x

def BuildTree(ceng, zhong):
    if len(ceng)==0:
        return None
    if len(ceng)==1:
        return TreeNode(ceng[0])
    else:
        flag=TreeNode(ceng[0])
        root=ceng[0]
        zong=zhong[:zhong.index(ceng[0])]
        cen=[]
        for i in ceng:
            if i in zong:
                cen.append(i)
        flag.left=BuildTree(cen,zong)
        cen = []
        zong=zhong[zhong.index(ceng[0])+1:]
        for i in ceng:
            if i in zong:
                cen.append(i)
        flag.right=BuildTree(cen,zong)
        return flag


def PrintLeafNode(root,node):
    if root==None:
        return
    if root.left==None and root.right==None:
        node.append(root.value)
    PrintLeafNode(root.left, node)
    PrintLeafNode(root.right, node)


def PreTravel(root,node):
    if root==None:
        return
    node.append(root.value)
    PreTravel(root.left, node)
    PreTravel(root.right, node)


def BackTravel(root, node):
    if root==None:
        return
    BackTravel(root.left, node)
    BackTravel(root.right, node)
    node.append(root.value)



ceng=input().strip().split(" ")
zhong=input().strip().split(" ")
root=BuildTree(ceng, zhong)
leaf=[]
pre=[]
back=[]
PrintLeafNode(root, leaf)
PreTravel(root, pre)
BackTravel(root, back)
print(" ".join(leaf))
print(" ".join(pre))
print(" ".join(back))

 

2018秋招小红书算法方向在线编程题

标签:tle   rip   nbsp   node   str   lag   分享   dtree   spl   

原文地址:https://www.cnblogs.com/tsdblogs/p/9672129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!