按之字形打印二叉树

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

python solution:

# -*- 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 []
        stack = [pRoot]
        res = []
        even = False
        while len(stack):
            l = len(stack)
            tempres = []
            for i in range(l):
                temp = stack.pop(0)
                tempres.append(temp.val)
                if temp.left:
                    stack.append(temp.left)
                if temp.right:
                    stack.append(temp.right)
            if not even:
                res.append(tempres)
                even = True
            else:
                even = False
                res.append(tempres[::-1])
        return res
上一篇:剑指offer--8.调整数组顺序使奇数位于偶数前面


下一篇:STL的function object concepts