Python中如何表示樹(shù)?
class Tree:
def __init__(self,entry,left=None,right=None):
self.entry=entry
self.left=left
self.right=right
def __repr__(self):
args=repr(self.entry)
if self.left or self.right:
args+=',{0},{1}'.format(repr(self.left),repr(self.right))
return 'Tree({0})'.format(args)
def square_tree(t):
if t==None:
return
else:
t.entry=t.entry**2
square_tree(t.left)
square_tree(t.right)
def height(t):
if t==None:
return 0
else:
return 1+max(height(t.left),height(t.right))
def size(t):
if t==None:
return 0
else:
return size(t.left)+size(t.right)+1
def find_path(t,x):
if t==None:
return None
elif t.entry==x:
return (x,)
left=find_path(t.left,x);right=find_path(t.right,x)
if left:
return (t.entry,)+left
elif right:
return (t.entry,)+right
else:
return None
t=Tree(2,Tree(7,Tree(2),Tree(6,Tree(5),Tree(11))),Tree(15))
print(t)
a=find_path(t,5)
print(a)