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('#')