Python 二叉树 先序中序后序 递归 和 非递归遍历、层次遍历

先建立一棵满二叉树,用三种递归的方式遍历,然后用三种非递归的方式遍历。

目录

1.定义一棵满二叉树的类,一个节点包括值,左右指针

2.建立一棵满二叉树,值在[0,14]之间

3.层次遍历:

 4.递归:前中后序

4.前序非递归遍历:栈

5.中序非递归遍历:栈

6.后序非递归:栈


1.定义一棵满二叉树的类,一个节点包括值,左右指针

import numpy as np
result_pre,result_in,result_post,result_f = [],[],[],[]
class BiTree:
    def __init__(self,r):
        self.val = r
        self.left = None
        self.right = None

2.建立一棵满二叉树,值在[0,14]之间

def creat_BiTree():
    x = np.arange(15)
    i = 1
    root = BiTree(x[0])
    r = root
    store = []
    store.append(root)
    k=0
    while i 

 输出结果:

0 1
0 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
4 10
5 11
5 12
6 13
6 14
0
1 2
3 4 5 6
7 8 9 10 11 12 13 14

3.层次遍历:

def floor(r):
    stack_f = []
    k = 0
    visited = []
    while r:

        #print("visited", visited)
        if r and r.val not in visited:
            stack_f.append(r)
            visited.append(r.val)

        if r.left and r.left.val not in visited:
            stack_f.append(r.left)
            visited.append(r.left.val)

        if r.right and r.right.val not in visited:
            stack_f.append(r.right)

            visited.append(r.right.val)
        k +=1
        if len(stack_f):
            r = stack_f[0]
            del stack_f[0]
        else :
            break
    result_f = visited
    #return visited
    print("result_f",result_f)
    return result_f

层次遍历输出

result_f [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

 4.递归:前中后序

def preOrder(r):
    if r:
        #print(result)
        result_pre.append(r.val)
        preOrder(r.left)
        preOrder(r.right)

def inOrder (r):
    if r:
        inOrder(r.left)
        result_in.append(r.val)
        #print(r.val)
        inOrder(r.right)
def postOrder(r):
    if r:
        postOrder(r.left)
        postOrder(r.right)
        result_post.append(r.val)
        #print(r.val)

三种递归遍历输出

pre order [0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14] in order [7, 3, 8, 1, 9, 4, 10, 0, 11, 5, 12, 2, 13, 6, 14] post order [7, 8, 3, 9, 10, 4, 1, 11, 12, 5, 13, 14, 6, 2, 0]

4.前序非递归遍历:栈

根节点先入栈,并且访问根节点的值。

1. 根入栈后一直判断是否有左节点,有就一直找左节点,并存储从根节点到最左节点的路过的节点、最左节点,并且访问路过的节点的值。找到最左孩子之后的栈中节点:0137

2.找到最左节点后,再从存储中出栈,判断最左节点是否有右孩子。如果有右孩子,那么将右孩子下的节点进行上述1.和2.的遍历,直到栈里的节点全被pop出去。

栈里有[0] 已访问[0]
[0, 1]
[0, 1, 3]
[0, 1, 3, 7]
[0, 1, 3]
[0, 1, 8]
[0, 1]
[0, 4]
[0, 4, 9]
[0, 4]
[0, 10]
[0]
[2]
[2, 5]
[2, 5, 11]
[2, 5]
[2, 12]
[2]
[6]
[6, 13]
[6]
[14]
[]
[0, 1]
[0, 1, 3]
[0, 1, 3, 7]
[0, 1, 3, 7]
[0, 1, 3, 7, 8]
[0, 1, 3, 7, 8]
[0, 1, 3, 7, 8, 4]
[0, 1, 3, 7, 8, 4, 9]
[0, 1, 3, 7, 8, 4, 9]
[0, 1, 3, 7, 8, 4, 9, 10]
[0, 1, 3, 7, 8, 4, 9, 10]
[0, 1, 3, 7, 8, 4, 9, 10, 2]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
def Non_recursive_Preorder(r):
    visied = [r]
    root = r
    store_val = [root.val]
    while visied:
        if root.left:
            root = root.left
            visied.append(root)#入栈
            store_val.append(root.val)#访问节点
        else:
            node = visied.pop()#出栈
            root = node
            if root.right:#访问右节点
                root = root.right
                visied.append(root)
                store_val.append(root.val)

    print('Non_recursive_Preorder',store_val)

输出

Non_recursive_Preorder [0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]

5.中序非递归遍历:用栈。

中序遍历的时候,栈里先入了根节点

1. 还是先找最左节点,visited存储根节点、从根节点到最左节点的中间节点、最左节点。

2. 找到最左节点后,从栈里pop一个节点,访问它的值。

如果有右节点,那么按照1. 和 2. 访问右子树,直到栈里没节点了。

def Non_recursive_inorder(r):
    root = r
    visited = []
    store_val = []
    visited.append(root)
    #store_val.append(root.val)
    while visited:
        if root.left:
            visited.append(root.left)
            root = root.left

        else:
            node = visited.pop()
            store_val.append(node.val)
            if node.right:
                root = node.right
                visited.append(node.right)
    print("recursive_Inorder",store_val)

输出

Non-recursive_Inorder [7, 3, 8, 1, 9, 4, 10, 0, 11, 5, 12, 2, 13, 6, 14]

6.后序非递归:栈。

后序非递归和前序非递归很像,前序是根左右,前序每次访问根节点的值,访问左孩子入栈,然后判断是否有右孩子。

后序非递归:

根节点先入栈,并且访问根节点的值。

先访问右孩子,再判断是否有左孩子,这是入栈顺序:先右再左。while循环之后,得到的序列是根右左的顺序,再将其逆序出栈顺序就是:左右根了。

简单来看就是将先序遍历先访问的根左右节点,后序非递归就是根右左,再逆序。将先序遍历的left换成right,就改变顺序了。

def Non_recursive_Postorder(r):
    visited = [r]
    s = []
    root = r
    store_val = [r.val]
    i =0
    while visited:
        if root.right:
            root = root.right
            visited.append(root)
            store_val.append(root.val)
        else:
            node = visited.pop()
            root = node
            if root.left:
                root = root.left
                visited.append(root)
                store_val.append(root.val)

    print('Non_recursive_Postorder',store_val[::-1])

输出:

Non_recursive_Postorder [7, 8, 3, 9, 10, 4, 1, 11, 12, 5, 13, 14, 6, 2, 0]
'''练习:
WC6 二叉树的后序遍历 :
https://www.nowcoder.com/practice/32af374b322342b68460e6fd2641dd1b?tpId=202&&tqId=38715&rp=1&ru=/activity/oj&qru=/ta/code-written-high/question-ranking

用递归的方法对给定的二叉树进行后序遍历。
例如:
给定的二叉树为{1,#,2,3},
返回[3,2,1].

题目给的并不是完全二叉树,所以用上面的方法一直会报错


'''
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#
# 
# @param root TreeNode类 
# @return int整型一维数组
'''非递归:'''
class Solution:
    def postorderTraversal(self , root ):
        if root==None:
          return []
        val = []
        visited = [root]
        while visited:
          node = visited.pop()
          val.append(node.val)
          if node.left:
            visited.append(node.left)
          if node.right:
            visited.append(node.right)
        return val[::-1]
'''递归'''
class Solution:
    def __init__(self):
      self.arr = []
    def postOrder(self,r):
      if r==None:
        return
      if r.left:
        self.postOrder(r.left)
      if r.right:
        self.postOrder(r.right)
      self.arr.append(r.val)
    def postorderTraversal(self , root ):
        
        re = self.postOrder(root)
        return self.arr

合集:

import numpy as np
result_pre,result_in,result_post,result_f = [],[],[],[]
class BiTree:
    def __init__(self,r):
        self.val = r
        self.left = None
        self.right = None
def preOrder(r):
    if r:
        #print(result)
        result_pre.append(r.val)
        preOrder(r.left)
        preOrder(r.right)

def inOrder (r):
    if r:
        inOrder(r.left)
        result_in.append(r.val)
        #print(r.val)
        inOrder(r.right)
def postOrder(r):
    if r:
        postOrder(r.left)
        postOrder(r.right)
        result_post.append(r.val)
        #print(r.val)

def floor(r):
    stack_f = []
    k = 0
    visited = []
    while r:

        #print("visited", visited)
        if r and r.val not in visited:
            stack_f.append(r)
            visited.append(r.val)

        if r.left and r.left.val not in visited:
            stack_f.append(r.left)
            visited.append(r.left.val)

        if r.right and r.right.val not in visited:
            stack_f.append(r.right)

            visited.append(r.right.val)
        k +=1
        if len(stack_f):
            r = stack_f[0]
            del stack_f[0]
        else :
            break
    result_f = visited
    #return visited
    print("result_f",result_f)
    return result_f

def creat_BiTree():
    x = np.arange(15)
    i = 1
    root = BiTree(x[0])
    r = root
    store = []
    store.append(root)
    k=0
    while i 

输出:

0 1
0 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
4 10
5 11
5 12
6 13
6 14
result_f [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
pre order [0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14] in order [7, 3, 8, 1, 9, 4, 10, 0, 11, 5, 12, 2, 13, 6, 14] post order [7, 8, 3, 9, 10, 4, 1, 11, 12, 5, 13, 14, 6, 2, 0]
Non-recursive_Inorder [7, 3, 8, 1, 9, 4, 10, 0, 11, 5, 12, 2, 13, 6, 14]
Non_recursive_Preorder [0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
Non_recursive_Postorder [7, 8, 3, 9, 10, 4, 1, 11, 12, 5, 13, 14, 6, 2, 0]

你可能感兴趣的:(日常Debug,python,二叉树)