按之字形顺序打印二叉树(二叉树的层次遍历)-演道网

题目描述

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

和把二叉树打印成多行(问题:链接)类似,都是对二叉树的层次遍历,只不过这个题要求正序逆序交叉输出

# -*- coding:utf-8 -*-
# class TreeNode:
#    def __init__(self, x):
#        self.val = x
#        self.left = None
#        self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
         return []

        flag = True
        result = []

        p = [pRoot]
        while p:
         res = []
         node = []

         for n in p:
          if n.left:
           node.append(n.left)
          if n.right:
           node.append(n.right)
          res.append(n.val)

         if flag == False:
          result.append(res[::-1])
          flag = True
         else:
          result.append(res)
          flag = False
         p = node

        return result

求二叉树中两个节点的最远距离 http://www.linuxidc.com/Linux/2016-08/134049.htm

根据二叉树的前序数组和中序序遍历数组生成二叉树 http://www.linuxidc.com/Linux/2016-09/135514.htm

判断一个二叉树是否是平衡二叉树 http://www.linuxidc.com/Linux/2016-07/132842.htm

轻松搞定面试中的二叉树题目 http://www.linuxidc.com/linux/2014-07/104857.htm

二叉树的先序、中序、后序遍历 http://www.linuxidc.com/Linux/2016-06/132504.htm

转载自演道,想查看更及时的互联网产品技术热点文章请点击http://go2live.cn