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

给定一个数组,构建二叉树,并且按层次打印这个二叉树
## 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)

猜你喜欢

转载自www.cnblogs.com/Yanss/p/12759926.html
今日推荐