二叉树序列化

1. 题目描述(题目链接)(此代码运行超时~作为笔者第一版记录~)

2. 思路

(1)根据层次遍历建立二叉树;

(2)先序遍历二叉树

3.代码

import sys
import math

class BinTree(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    # 按层次建立二叉树
    def createBinTree(self, inputList):

        # 尚未设置子节点的节点列表
        nodeList = []

        if (inputList == None) or (len(inputList) == 0):
            return None
        # 取出根元素
        value = inputList.pop(0)
        root = BinTree(value)
        nodeList.append(root)

        # 结束条件:所有值不为“#”的节点都设置了子节点,即nodeList为空
        while len(nodeList) > 0:
            leftValue = inputList.pop(0)
            rightValue = inputList.pop(0)
            if leftValue != '#' and rightValue != '#':
                nodeLeft = BinTree(leftValue)
                nodeRight = BinTree(rightValue)

                # 每次取出两个节点,加入到 “未设置子节点的节点列表”
                nodeList.append(nodeLeft)
                nodeList.append(nodeRight)
                nodeList[0].left = nodeLeft
                nodeList[0].right = nodeRight

                # 为节点设置子节点后移出队列
                nodeList.pop(0)

            # 若值为#,不需要处理,默认情况下节点的左右节点都为None
            elif leftValue == '#' and rightValue != '#':
                nodeRight = BinTree(rightValue)
                nodeList.append(nodeRight)
                nodeList[0].right = nodeRight
                nodeList.pop(0)
            elif rightValue == '#' and leftValue != '#':
                nodeLeft = BinTree(leftValue)
                nodeList.append(nodeLeft)
                nodeList[0].left = nodeLeft
                nodeList.pop(0)
            else:
                nodeList.pop(0)
        return root

    def pre_traversal(self,tree):
        if tree != None:
            print(tree.val)
            self.pre_traversal(tree.left)
            self.pre_traversal(tree.right)
        else:
            print('#')
            

n = int(sys.stdin.readline().strip())
if n > 0:
    inputList = [sys.stdin.readline().strip() for i in range(n)]

    m = len(inputList)
    nodes = abs(int(pow(2,int(math.log2(m)-1))-1))
    num = len([each for each in inputList[nodes:] if each != '#'])
    inputList += ['#']*(2*num)
    
    s = Solution()
    root = s.createBinTree(inputList)
    s.pre_traversal(root)
else:
    print('#')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值