class BtreeNote():
def __init__(self,data=None,left=None,right=None):
self.data =data
self.left=left
self.right = right
self._c =0
def count_Note(self,t):# 实例化 t 类内的函数,必须偏离化self
if t ==None:
return 0
else:
self._c += 1
if not isinstance(t,int):
self.count_Note(t.left)
self.count_Note(t.right)
return self._c
def travel(self,t): # 深度优先基于递归的前序遍历
if t is not None and not isinstance(t ,int):
print(t.data)
elif isinstance(t ,int):
print(t)
else:
return 0
if not isinstance(t ,int):
self.travel(t.left) # 这就是递归的强大,你只需要考虑一次
self.travel(t.right)
t=BtreeNote(1,BtreeNote(2),BtreeNote(2,3,BtreeNote(1,3)))
print(t.count_Note(t))
t.travel(t)
基于递归的前序二叉树遍历实现
最新推荐文章于 2022-10-22 11:16:59 发布