python实现树的前序/中序/后序遍历以及深度/广度遍历等

本文深入探讨了二叉树的多种遍历方法,包括深度优先搜索(DFS)、广度优先搜索(BFS)、前序遍历、中序遍历、后序遍历及其变种。通过具体代码实现,展示了如何构建二叉树并进行遍历,同时提供了遍历结果的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:


class Node():
    def __init__(self, x):
        self.val = x
        self.left = self.right = None
        

class Tree():
    def __init__(self):
        self.root = None
    
    def add(self, x):
        node = Node(x)
        if self.root is None:
            self.root = node
        else:
            s = [self.root]
            while s:
                curr = s.pop(0)
                if curr.left is None:
                    curr.left = node
                    return
                if curr.right is None:
                    curr.right = node
                    return
                
                s.append(curr.left)
                s.append(curr.right)
    def show(self):
        if self.root is not None:
            s = [self.root]
            result = []
            while s:
                curr = s.pop(0)
                result.append(curr.val)
                if curr.left is not None:
                     s.append(curr.left)
                if curr.right is not None:
                    s.append(curr.right)
            print(result)

    def dfs(self):
        print("dfs")
        if self.root is None:
            return
        result=[]
        s=[self.root]
        while s:
            curr = s.pop()
            result.append(curr.val)
            if curr.right is not None:
                s.append(curr.right)
            if curr.left is not None:
                s.append(curr.left)
        print(result)
            
    def bfs(self):
        print("bfs")
        if self.root is None:
            return
        result =[]
        s=[self.root]
        while s:
            curr = s.pop(0)
            result.append(curr.val)
            if curr.left is not None:
                s.append(curr.left)
            if curr.right is not None:
                s.append(curr.right)
        print(result)
        
    def preorder(self):
        print("pre-order:")
        if self.root is None:
            return
        result =[]
        s=[self.root]
        while s:
            curr = s.pop()
            result.append(curr.val)
            if curr.right is not None:
                s.append(curr.right)
            if curr.left is not None:
                s.append(curr.left)
        print(result)
        
    def inorder(self):
        print("in-order:")
        if self.root is None:
            return
        s = []
        result =[]
        curr = self.root
        while curr or s:
            while curr:  # 从根结点开始,寻找左子树,把它压入栈中
                s.append(curr)
                curr = curr.left
            curr = s.pop() 
            result.append(curr.val)
            curr = curr.right  
        print(result)
        
    def postorder(self):
        print("post-order:")
        if self.root is None:
            return
        s = [ (self.root, False)] #(node, is_visited?)
        result = []
        while s:
            curr, is_visited = s.pop()
            if curr is not None:
                if is_visited:
                    result.append(curr.val)
                else:
                    s.append((curr,True))
                    s.append((curr.right, False))
                    s.append((curr.left, False))
        print(result)    
    def postorder2(self):
        print("post-order2: ")
        if self.root is None:
            return
        result =[]
        s=[self.root]
        while s:
            curr = s.pop()
            result.append(curr.val)
            if curr.left is not None:
                s.append(curr.left)
            if curr.right is not None:
                s.append(curr.right)
        print(result[::-1])




if __name__ == '__main__':
    t=Tree()
    n = 15
    for i in range(n):
        t.add(i)

    print("maxdepth:",maxDepth(t.root))
    print("mindepth:",minDepth(t.root))
    t.dfs()
    t.bfs()
    t.preorder()
    t.inorder()
    t.postorder()
    t.postorder2()
'''
maxdepth: 4
mindepth: 4
dfs
[0, 1, 3, 7, 8, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
bfs
[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]
post-order2: 
[7, 8, 3, 9, 10, 4, 1, 11, 12, 5, 13, 14, 6, 2, 0]
'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值