首页 > 其他 > 详细

广度遍历和深度遍历二叉树

时间:2020-04-23 13:12:54      阅读:91      评论:0      收藏:0      [点我收藏+]
给定一个数组,构建二叉树,并且按层次打印这个二叉树
## 14 二叉树节点
class Node(object):
  def __init__(self, data, left=None, right=None):
    self.data = data
    self.left = left
    self.right = right
tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5),
Node(4)))
 
## 15 层次遍历
def lookup(root):
  stack = [root]
  while stack:
    current = stack.pop(0)
    print current.data
    if current.left:
      stack.append(current.left)
    if current.right:
      stack.append(current.right)
## 16 深度遍历
def deep(root):
  if not root:
    return
  print root.data
  deep(root.left)
  deep(root.right)
 
if __name__ == ‘__main__‘:
lookup(tree)
deep(tree)

广度遍历和深度遍历二叉树

原文:https://www.cnblogs.com/Yanss/p/12759926.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!