python中treenode_python 树的初始化与三种递归遍历,求二叉树node个数与树深度

class Node(object):

def __init__(self,elem):

self.elem=elem

self.lchild=None

self.rchild=None

class Tree(object):

def __init__(self):

self.root=None

def add(self,elem):#二叉树,添加一个元素

node=Node(elem=elem)

if self.root is None:

self.root=node

return

queue=[self.root]

while queue:

cur_node=queue.pop(0)

if cur_node.lchild is None:

cur_node.lchild=node

return

else:

queue.append(cur_node.lchild)

if cur_node.rchild is None:

cur_node.rchild=node

return

else:

queue.append(cur_node.rchild)

def preorder(self,node): #根左右,递归

if node is None:

return

print(node.elem,end=' ')

self.preorder(node.lchild)

self.preorder(node.rchild)

# 先序打印二叉树(非递归)

def preOrderTraverse(self,node):

stack = [node]

while stack:

node = stack.pop()

print(node.elem,end=' ')

if node.rchild is not None:

stack.append(node.rchild)

if node.lchild is not None:

stack.append(node.lchild)

def inorder(self,node):#左根右,递归

if node is None:

return

self.inorder(node.lchild)

print(node.elem,end=' ')

self.inorder(node.rchild)

def postorder(self,node):#左根右,递归

if node is None:

return

self.postorder(node.lchild)

self.postorder(node.rchild)

print(node.elem,end=' ')

# 求二叉树节点个数

def treeNodenums(self,node):

if node is None:

return 0

nums = self.treeNodenums(node.lchild)

nums += self.treeNodenums(node.rchild)

return nums + 1

# 二叉树的最大深度

def bTreeDepth(self,node):

if node is None:

return 0

ldepth = bTreeDepth(node.lchild)

rdepth = bTreeDepth(node.rchild)

return (max(ldepth, rdepth) + 1)

if __name__ == '__main__':

tree=Tree()

for i in range(10):

tree.add(i)

tree.postorder(tree.root)

print('\n')

tree_nums=tree.treeNodenums(tree.root)

print(tree_nums)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值