1-二叉树 遍历

二叉树遍历分为前序、中序和后序遍历,其中在左子树肯定比右子树先遍历的条件下按根节点的位置确定是哪种遍历方式,即根节点在最开始遍历为先序遍历,根节点在中间遍历为中序遍历,根节点在后面遍历为后序遍历。

代码模板:

# 递归方式
def perorder(root):
    if not root:
        return
    do(root)
    preorder(root.left)
    preorder(root.right)
    return

def inorder(root):
    if not root:
        return
    preorder(root.left)
    do(root)
    preorder(root.right)
    return

def postorder(root):
    if not root:
        return
    preorder(root.left)
    preorder(root.right)
    do(root)
    return

# 非递归方式
def preorder(root):
    if not root:
         return 
   
    e_stack = []
    e_stack.append(root)

    while len(e_stack) > 0:
        node = e_stack.pop()
        do(node)
        if node.right:
            e_stack.append(node.right)
        if node.left:
            e_stack.append(node.left)


def inorder(root):
    if not root:
        return
    left_stack = []
    node = root
    while node or len(left_stack) > 0:
        if node:
            left_stack.append(node)
            node = node.left
        else:
            node = left_stack.pop()
            do(node)
            node = node.right


BFS
from collections import deque
def bfs(root):
  if not root:
    return
    
  bfs = deque([root])
  while len(bfs) > 0:
    for _ in range(len(bfs)):
      node = bfs.popleft()
      do(node)
      if node.left:
        bfs.append(node.left)
      if node.right:
        bfs.append(node.right)

  

 

posted @ 2020-09-23 15:42  哈哈哈喽喽喽  阅读(155)  评论(0编辑  收藏  举报