剑指offer-按之字形顺序打印二叉树(python)

思路:先把每个都放在res中,在根据奇偶行换位置。

#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        tmp=[pRoot]
        res=[]
        tmp2=[]
        tmp1=[]
        while tmp:
            for i in tmp:
                tmp2.append(i.val)
                if  i.left:
                    tmp1.append(i.left)
                if  i.right:
                    tmp1.append(i.right)
            res.append(tmp2)
            tmp=tmp1
            tmp2=[]
            tmp1=[]
        final=[]
        for i in range(len(res)):
            if i%2==0:
                final.append(res[i])
            else:
                final.append(res[i][::-1])
        return final

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104617639
今日推荐