A few days ago suddenly interested in Python, learned a few days also feel it is very concise and practical. Broke my so long time on Java C # C and VB aesthetic fatigue, let me a bright. "It's as simple as reading English," said the remark, which Python says is reasonable.
I am very fond of Python because I have heard that many Google programs are used in Python, and in Google App Engine and support Python. If you go to a Google interview or a written exam, it's likely that you'll get to the question: Using Python to implement tree traversal.
I tried to write a bit, but after all, is a rookie, there are questions please advise.
The results are as follows:
The source program is as follows:
#!user/bin/python
#树的实体 (including Id, value, Fatherid)
Class TreeModel:
"Tree View"
def __init__ (Self,id,value,fatherid):
Self. Id=id
Self.value=value
Self.fatherid=fatherid
Def show (self):
Return Self.value
# The traversal and display of the tree
Class Treeshow:
"Tree Show"
Loglist = [TreeModel (0, ' Addtree ', 0)] #记录已经遍历过的节点
Writtenlist = [TreeModel (0, ' Addtree ', 0)] #记录已经打印出的节点
def __init__ (self,rootid,list):
Self.rootid = Rootid
Self.list=list
#通过Id获取节点
def Getmodelbyid (Self,id):
For T in Self.list:
if t.id = = Id:
Return T
Return None
#判断是否有子节点
def havechild (self,t):
For T1 in Self.list:
if T1.fatherid = = T.id and not self. Isinloglist (T1):
Return True
Return False
#获取第一个没有遍历的子节点
def getfirstchild (self,t):
For T1 in Self.list:
if T1.fatherid = = T.id and not self. Isinloglist (T1):
return T1
Return None
#判断某节点是否已经被遍历
def isinloglist (self,t):
For T1 in Self.loglist:
if T1. Id = = T.id:
Return True
Return False
#判断某节点是否已经打印
def isinwrittenlist (self,t):
For T1 in Self.writtenlist:
if T1. Id = = T.id:
Return True
Return False
#获取父节点
def getfathertree (self,t):
For T1 in Self.list:
if T1. Id = = T.fatherid:
return T1
Return None
#遍历打印
Def show (self):
Currenttree = Self.getmodelbyid (Self.rootid)
s = '
Strnum = 1
while (True):
If Self.havechild (currenttree):
If not self. Isinwrittenlist (Currenttree):
Print S*strnum,currenttree.show ()
Self.writtenList.append (Currenttree)
Currenttree = Self.getfirstchild (currenttree)
Strnum + = 1
Continue
Else
if (currenttree.id = = Self.rootid):
Break
Else
If not self. Isinwrittenlist (Currenttree):
Print S*strnum,currenttree.show ()
Self.logList.append (Currenttree)
Currenttree = Self.getfathertree (currenttree)
Strnum-= 1
Continue
#初始化一些节点实例
T1 = TreeModel (1, ' A-1 ', 0)
T2 = TreeModel (2, ' B-1 ', 1)
T3 = TreeModel (3, ' B-2 ', 1)
T4 = TreeModel (4, ' C-1 ', 2)
T5 = TreeModel (5, ' C-2 ', 2)
T6 = TreeModel (6, ' C-3 ', 3)
T7 = TreeModel (7, ' C-4 ', 3)
T8 = TreeModel (8, ' D-1 ', 4)
T9 = TreeModel (9, ' E-1 ', 8)
T10 = TreeModel (Ten, ' E-2 ', 8)
#将这些节点实例链式存储起来 (as stored in a database)
List = [T1,t2,t3,t4,t5,t6,t7,t8,t9,t10]
#调用展示
ts = treeshow (1,list)
Ts.show ()
If Google interview lets you write a tree traversal program in Python