Python中如何表示树

寂寞不是我 2个月前 已收到1个回答 举报

情深丨 4星

共回答了43个问题采纳率:93.7% 评论

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)

21小时前

37
可能相似的问题

猜你喜欢的问题

热门问题推荐

Copyright © 2024 微短问答 All rights reserved. 粤ICP备2021119249号 站务邮箱 959505@qq.com