1. 程式人生 > >Python實現二叉樹的層次遍歷及按層輸出的兩種方法

Python實現二叉樹的層次遍歷及按層輸出的兩種方法

二叉樹的層次遍歷

二叉樹的層次遍歷即從上往下、從左至右依次列印樹的節點。
其思路就是將二叉樹的節點加入佇列,出隊的同時將其非空左右孩子依次入隊,出隊到佇列為空即完成遍歷。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回從上到下每個節點值列表,例:[1,2,3]
    def PrintFromTopToBottom
(self, root):
# write code here outList=[] queue=[root] while queue!=[] and root: outList.append(queue[0].val) if queue[0].left!=None: queue.append(queue[0].left) if queue[0].right!=None: queue.append(queue[0
].right) queue.pop(0) return outList

在python中,佇列是用列表來模擬的,其中pop(0)的操作複雜度是O(n),下面不用佇列作為改進。

    def PrintFromTopToBottom(self, root):
        if not root:
            return []
        currentStack = [root]
        outList= []
        while currentStack:
            nextStack = []
            for
point in currentStack: if point.left: nextStack.append(point.left) if i.right: nextStack.append(point.right) outList.append(point.val) currentStack = nextStack return outList

二叉樹的按層輸出

二叉樹的按層輸出即從上往下、從左至右依次列印樹的節點。每一層輸出一行。

這一題和上一題的區別主要在於要區別開每一層,即不僅按層遍歷還要按層輸出。難點在於有的層會缺項,即不是完全二叉樹。但根據層次遍歷的特點,節點會按層依次的進入佇列,利用這一特點來區分每一層。

上面問題改進版中即是按層儲存在每一個列表中的,也適合解決該問題

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二維列表[[0],[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        queue=[pRoot]
        outList=[]
        while queue:
            res=[]
            nextQueue=[]
            for point in queue:     #這裡再遍歷每一層
                res.append(point.val)
                if point.left:
                    nextQueue.append(point.left)
                if point.right:
                    nextQueue.append(point.right)
            outList.append(res)
            queue=nextQueue     #這一步很巧妙,用當前層覆蓋上一層
        return outList

當然,完全用佇列來做也是沒有問題的,不過,其關鍵在於確認每一層的分割點,因此可以用一個標誌位來記錄這個分割點的位置

    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        queue=[pRoot]
        outList=[]
        while queue:
            res=[]
            i=0
            numberFlag=len(queue)   #這一步記錄當前層中節點的個數
            while i <numberFlag:    #這裡再遍歷每一層
                point=queue.pop(0)
                res.append(point.val)
                if point.left:
                    queue.append(point.left)
                if point.right:
                    queue.append(point.right)
                i+=1
            outList.append(res)
        return outList