面试算法题

"""假设前端同学通过接口向后端传了天猫的行业信息,例如:
industry_list = [
{
"parent_ind" : "女装",
"name" : "连衣裙"
},
{
"name": "女装"
},
{
"parent_ind" : "女装",
"name" : "半身裙"
},
{
"parent_ind" : "女装",
"name" : "A字裙"
},
{
"name": "数码"
},
{
"parent_ind" : "数码",
"name": "电脑配件"
},
{
"parent_ind" : "电脑配件",
"name": "内存"
},
]

为了取用方便,我们希望可以将其转换为树状格式,例如:
{
"数码": {
"电脑配件": {
"内存" : {}
}
},
"女装" : {
"连衣裙": {},
"半身裙": {},
"A字裙": {}
}
}
实现一个方法完成这个转换,时间复杂度请控制在O(n)
"""

def convert_format(data):
    tree_dict = {}
    dict1 = {}  # 所有key
    for item_dic in data:
        name = item_dic.get("name")
        parent = item_dic.get("parent_ind")
        son_dic = {name: {}}
        if not parent:
            dict1[name] = tree_dict.setdefault(name, {})
        else:
            if tree_dict.get(parent) == None and dict1.get(parent) == None:
                tree_dict[parent] = son_dic
            dict1.update(son_dic)
            dict1.setdefault(parent, {}).update(son_dic)
    return tree_dict

二叉树广度优先遍历,和其变种“Z“字遍历

# 定义一个树节点
class TreeNode:
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left     # 左子树
        self.right = right   # 右子树

# 实例化一个树节点
node1 = TreeNode("A",
                 TreeNode("B",
                          TreeNode("D", TreeNode("H")),
                          TreeNode("E", TreeNode("I"))
                          ),
                 TreeNode("C",
                          TreeNode("F"),
                          TreeNode("G")
                          )
                 )


def levelOrder(tree):
    if tree is None:
        return []
    q = []
    q.append(tree)

    while len(q) != 0:
        for i in range(len(q)):
            r = q.pop(0)
            if r.left is not None:
                q.append(r.left)
            if r.right is not None:
                q.append(r.right)
            print(r.value)


def leve10der_z(node):
    # z字遍历
    if node is None:
        return []
    q = []
    q.append(node)

    num = 0 # 控制同层节点遍历方向
    s = ''
    while len(q) != 0:
        num += 1
        print(num)
        lenght = len(q)
        s_item = ''
        for i in range(lenght):
            # 控制同层节点遍历方向
            r = q.pop(0)
            if r.left is not None:
                # 非空左孩子入队
                q.append(r.left)
            if r.right is not None:
                # 非空右孩子入队
                q.append(r.right)
            s_item = s_item + r.value

        if num % 2 == 0:
            s_item = s_item[::-1]
        s = s + s_item

    print(s)


if __name__ == "__main__":
    # levelOrder(node1)
    leve10der_z(node1)

 

posted @ 2020-07-30 17:01  清风_Z  阅读(288)  评论(0编辑  收藏  举报