剑指Offer_编程题59:按之字顺序打印二叉树

题目:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

牛客网:链接

有两种方法。第一种:按序获取每一层节点的值;然后将偶数层节点的值倒序。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:  
    def Print(self, pRoot):  
        if not pRoot:  
            return []  
        nodeStack = [pRoot]  
        result = []  
        times = 0
        while nodeStack:
            times += 1
            res = []  
            nextStack = []  
            for i in nodeStack:  
                res.append(i.val)  
                if i.left:  
                    nextStack.append(i.left)  
                if i.right:  
                    nextStack.append(i.right)  
            nodeStack = nextStack
            if times % 2 == 0:
                res = res[::-1]
                         
            result.append(res)  
        return result  

第二种。获取每一层的节点的值时,如果是偶数层,则将每个节点的值插入到列表的头部,即实现了获取节点值时如果是偶数层则倒序排列的效果。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:  
    def Print(self, pRoot):  
        if not pRoot:  
            return []  
        nodeStack = [pRoot]  
        result = []  
        times = 0
        while nodeStack:
            times += 1
            res = []  
            nextStack = []  
            for i in nodeStack:  
                if times % 2 == 0:
                    res.insert(0, i.val)
                else:
                    res.append(i.val)  
                if i.left:  
                    nextStack.append(i.left)  
                if i.right:  
                    nextStack.append(i.right)  
            nodeStack = nextStack                        
            result.append(res)  
        return result  

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/82900537