python实现二叉树的遍历

# 二叉树的广度优先遍历
class Node(object):
  def __init__(self, item):
    self.elem = item
    self.lchild = None
    self.rchild = None

class Tree(object):
  # 二叉树
  def __init__(self):
    self.root = None

  def add(self, item):
    # 广度优先使用队列实现,一边存,另一边取
    node = Node(item)
    if self.root is None:
      self.root = node
      return
    # 构造队列时将根节点添加进来
    queue = [self.root]
    # print(queue)
    # 队列不为空时,寻找待插入的位置
    while queue:
      # 从队列中读取当前节点
      cur_node = queue.pop(0)
      # print(cur_node)
      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)
    # print(queue)

  def breadth_travel(self):
    # 广度优先遍历
    if self.root is None:
      return
    queue = [self.root]
    while queue:
      cur_node = queue.pop(0)
      print(cur_node.elem, end=" ")
      if cur_node.lchild is not None:
        queue.append(cur_node.lchild)
      if cur_node.rchild is not None:
        queue.append(cur_node.rchild)
  
  def pre_order(self, node):
    # 前序遍历,根左右
    if node is None:
      return
    print(node.elem, end=" ")
    self.pre_order(node.lchild)
    self.pre_order(node.rchild)

  def in_order(self, node):
    # 中序遍历:左根右
    if node is None:
      return
    self.in_order(node.lchild)
    print(node.elem, end=" ")
    self.in_order(node.rchild)


  def post_order(self, node):
    # 后序遍历:左右根
    if node is None:
      return
    self.post_order(node.lchild)
    self.post_order(node.rchild)
    print(node.elem, end=" ")


if __name__ == '__main__':
  tree = Tree()
  tree.add('A')
  tree.add('B')
  tree.add('C')
  tree.add('D')
  tree.add('E')
  tree.add('F')
  # 广度优先遍历
  tree.breadth_travel()
  print(" ")
  
  # 前序遍历
  node = Node('S')
  # tree.pre_order(node)
  tree.pre_order(tree.root)
  print(" ")

  # 中序遍历
  tree.in_order(tree.root)
  print(" ")

  # 后序遍历
  tree.post_order(tree.root)
  print(" ")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值